בקטע הזה מתואר ה-API של המקודד והמפענח שכלולים בספריית WebP. תיאור ה-API הזה מתייחס לגרסה 1.4.0.
כותרות וספריות
כשמתקינים את libwebp
, ספרייה בשם webp/
תותקן במיקום האופייני של הפלטפורמה. לדוגמה, בפלטפורמות Unix, קובצי הכותרות הבאים יועתקו אל /usr/local/include/webp/
.
decode.h
encode.h
types.h
הספריות ממוקמות בספריות הספריות הרגילות. הספריות הסטטיות והדינמיות נמצאות ב-/usr/local/lib/
בפלטפורמות Unix.
ממשק API פשוט לפענוח קוד
כדי להתחיל להשתמש ב-decoding API, עליכם לוודא שהתקנתם את קובצי הספרייה והכותרות כפי שמתואר למעלה.
כוללים את הכותרת של decoding API בקוד C/C++ באופן הבא:
#include "webp/decode.h"
int WebPGetInfo(const uint8_t* data, size_t data_size, int* width, int* height);
הפונקציה הזו תאמת את כותרת התמונה ב-WebP ותאחזר את הרוחב והגובה של התמונה. אפשר להעביר את המצביעים *width
ו-*height
NULL
אם הם נקבעו כלא רלוונטיים.
מאפייני קלט
- נתונים
- נתוני תמונה של מצביעים ל-WebP
- data_size
- זה הגודל של בלוק הזיכרון שעליו מצביע
data
, שמכיל את נתוני התמונה.
החזרות
- false
- הוחזר קוד שגיאה במקרה של (א) שגיאות פורמט.
- true
- ההצלחה.
*width
ו-*height
תקפים רק להחזרה מוצלחת. - רוחב
- ערך של מספר שלם. הטווח מוגבל מ-1 ל-16383.
- גובה
- ערך של מספר שלם. הטווח מוגבל מ-1 עד 16383.
struct WebPBitstreamFeatures {
int width; // Width in pixels.
int height; // Height in pixels.
int has_alpha; // True if the bitstream contains an alpha channel.
int has_animation; // True if the bitstream is an animation.
int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
}
VP8StatusCode WebPGetFeatures(const uint8_t* data,
size_t data_size,
WebPBitstreamFeatures* features);
הפונקציה הזו תאחזר תכונות מה-bitstream. המבנה *features
מלא במידע שנאסף מה-bitstream:
מאפייני קלט
- נתונים
- נתוני תמונה של מצביעים ל-WebP
- data_size
- זה הגודל של בלוק הזיכרון שעליו מצביע
data
, שמכיל את נתוני התמונה.
החזרות
VP8_STATUS_OK
- כשהתכונות מאוחזרות בהצלחה.
VP8_STATUS_NOT_ENOUGH_DATA
- כשיש צורך בנתונים נוספים כדי לאחזר את התכונות מכותרות.
במקרים אחרים, ערכי שגיאה נוספים מסוג VP8StatusCode
.
- תכונות
- מצביעה למבנה WebPBitstreamFeatures.
uint8_t* WebPDecodeRGBA(const uint8_t* data, size_t data_size, int* width, int* height);
uint8_t* WebPDecodeARGB(const uint8_t* data, size_t data_size, int* width, int* height);
uint8_t* WebPDecodeBGRA(const uint8_t* data, size_t data_size, int* width, int* height);
uint8_t* WebPDecodeRGB(const uint8_t* data, size_t data_size, int* width, int* height);
uint8_t* WebPDecodeBGR(const uint8_t* data, size_t data_size, int* width, int* height);
הפונקציות האלה מפענחות תמונת WebP שאליה מפנה data
.
- הפונקציה
WebPDecodeRGBA
מחזירה דוגמאות של תמונות RGBA בסדר של[r0, g0, b0, a0, r1, g1, b1, a1, ...]
. - הפונקציה
WebPDecodeARGB
מחזירה דוגמאות של תמונות בפורמט ARGB בסדר של[a0, r0, g0, b0, a1, r1, g1, b1, ...]
. - הפונקציה
WebPDecodeBGRA
מחזירה דוגמאות של תמונות BGRA בסדר[b0, g0, r0, a0, b1, g1, r1, a1, ...]
. - הפונקציה
WebPDecodeRGB
מחזירה דוגמאות של תמונות RGB בסדר של[r0, g0, b0, r1, g1, b1, ...]
. - הפונקציה
WebPDecodeBGR
מחזירה דוגמאות של תמונות ב-BGR בסדר של[b0, g0, r0, b1, g1, r1, ...]
.
הקוד שקורא לכל אחת מהפונקציות האלה חייב למחוק את מאגר הנתונים הזמני (uint8_t*)
שהוחזר על ידי הפונקציות האלה באמצעות WebPFree()
.
מאפייני קלט
- נתונים
- נתוני תמונה של מצביעים ל-WebP
- data_size
- זה הגודל של בלוק הזיכרון שעליו מצביע
data
, שמכיל את נתוני התמונה - רוחב
- ערך של מספר שלם. הטווח מוגבל כרגע מ-1 ל-16383.
- גובה
- ערך של מספר שלם. הטווח מוגבל מ-1 עד 16383 כרגע.
החזרות
- uint8_t*
- מצביעים על דוגמאות של תמונות WebP מפוענחות בסדר RGBA/ARGB/BGRA/RGB/BGR לינארי, בהתאמה.
uint8_t* WebPDecodeRGBAInto(const uint8_t* data, size_t data_size,
uint8_t* output_buffer, int output_buffer_size, int output_stride);
uint8_t* WebPDecodeARGBInto(const uint8_t* data, size_t data_size,
uint8_t* output_buffer, int output_buffer_size, int output_stride);
uint8_t* WebPDecodeBGRAInto(const uint8_t* data, size_t data_size,
uint8_t* output_buffer, int output_buffer_size, int output_stride);
uint8_t* WebPDecodeRGBInto(const uint8_t* data, size_t data_size,
uint8_t* output_buffer, int output_buffer_size, int output_stride);
uint8_t* WebPDecodeBGRInto(const uint8_t* data, size_t data_size,
uint8_t* output_buffer, int output_buffer_size, int output_stride);
הפונקציות האלה הן וריאנטים של האפשרויות שלמעלה ומפענחות את התמונה ישירות למאגר נתונים זמני שהוקצה מראש output_buffer
. נפח האחסון המקסימלי שזמין במאגר הנתונים הזמני הזה מצוין על ידי output_buffer_size
. אם נפח האחסון הזה לא מספיק (או שאירעה שגיאה), מוחזר NULL
. אחרת, מטעמי נוחות, הערך output_buffer
מוחזר.
הפרמטר output_stride
מציין את המרחק (בבייטים) בין שורות הסריקה. לכן, הערך של output_buffer_size
צפוי להיות לפחות output_stride * picture - height
.
מאפייני קלט
- נתונים
- נתוני תמונה של מצביעים ל-WebP
- data_size
- זה הגודל של בלוק הזיכרון שעליו מצביע
data
, שמכיל את נתוני התמונה - output_buffer_size
- ערך של מספר שלם. גודל מאגר הנתונים הזמני שהוקצה
- output_stride
- ערך של מספר שלם. מציין את המרחק בין הסריקות.
החזרות
- output_buffer
- מצביעים על תמונת WebP מפוענחת.
- uint8_t*
output_buffer
אם הפונקציה מצליחה. אחרת,NULL
.
ממשק API לפענוח מתקדם
פענוח WebP תומך ב-API מתקדם שמאפשר לבצע חיתוך והתאמה לעומס (scaling) תוך כדי תנועה. היכולת הזו שימושית במיוחד בסביבות בהגבלת זיכרון, כמו טלפונים ניידים. בעיקרון, השימוש בזיכרון יותאם לגודל של הפלט, ולא בהתאם לגודל הקלט כשצריך רק תצוגה מקדימה מהירה או תמונה מוגדלת בחלק מתמונה אחרת שגדולה מדי. אפשר גם לשמור בטעות חלק מהמעבדים.
פענוח WebP מגיע בשתי גרסאות, כלומר, פענוח תמונה מלאה ופענוח מצטבר על-ידי חטיפי קלט קטנים. המשתמשים יכולים גם לספק מאגר זיכרון חיצוני כדי לפענח את התמונה. דוגמת הקוד הבאה מציגה את שלבי השימוש ב-API לפענוח מתקדם.
תחילה עלינו לאתחל אובייקט תצורה:
#include "webp/decode.h"
WebPDecoderConfig config;
CHECK(WebPInitDecoderConfig(&config));
// One can adjust some additional decoding options:
config.options.no_fancy_upsampling = 1;
config.options.use_scaling = 1;
config.options.scaled_width = scaledWidth();
config.options.scaled_height = scaledHeight();
// etc.
אפשרויות הפענוח נאספים בתוך המבנה WebPDecoderConfig
:
struct WebPDecoderOptions {
int bypass_filtering; // if true, skip the in-loop filtering
int no_fancy_upsampling; // if true, use faster pointwise upsampler
int use_cropping; // if true, cropping is applied first
int crop_left, crop_top; // top-left position for cropping.
// Will be snapped to even values.
int crop_width, crop_height; // dimension of the cropping area
int use_scaling; // if true, scaling is applied afterward
int scaled_width, scaled_height; // final resolution
int use_threads; // if true, use multi-threaded decoding
int dithering_strength; // dithering strength (0=Off, 100=full)
int flip; // if true, flip output vertically
int alpha_dithering_strength; // alpha dithering strength in [0..100]
};
אפשר לקרוא את תכונות ה-bitstream ב-config.input
, למקרה שנצטרך לדעת אותן מראש. למשל, כדאי לדעת אם בתמונה יש שקיפות מסוימת. שימו לב שהפעולה הזו גם תנתח את הכותרת של ה-bitstream, ולכן זו דרך טובה לדעת אם ה-bitstream נראה כמו WebP תקין.
CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
לאחר מכן עלינו להגדיר את מאגר הנתונים הזמני לפענוח, למקרה שנרצה לספק אותו ישירות במקום להסתמך על המפענח להקצאה. אנחנו צריכים לספק רק את הסמן לזיכרון וגם את הגודל הכולל של המאגר ושורת הקו (מרחק בבייטים בין שורות הסריקה).
// Specify the desired output colorspace:
config.output.colorspace = MODE_BGRA;
// Have config.output point to an external buffer:
config.output.u.RGBA.rgba = (uint8_t*)memory_buffer;
config.output.u.RGBA.stride = scanline_stride;
config.output.u.RGBA.size = total_size_of_the_memory_buffer;
config.output.is_external_memory = 1;
התמונה מוכנה לפענוח. יש שתי וריאנטים אפשריים לפענוח התמונה. אנחנו יכולים לפענח את התמונה בבת אחת באמצעות:
CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
לחלופין, אנחנו יכולים להשתמש בשיטה המצטברת כדי לפענח את התמונה בהדרגה ככל שיש בייטים חדשים זמינים:
WebPIDecoder* idec = WebPINewDecoder(&config.output);
CHECK(idec != NULL);
while (additional_data_is_available) {
// ... (get additional data in some new_data[] buffer)
VP8StatusCode status = WebPIAppend(idec, new_data, new_data_size);
if (status != VP8_STATUS_OK && status != VP8_STATUS_SUSPENDED) {
break;
}
// The above call decodes the current available buffer.
// Part of the image can now be refreshed by calling
// WebPIDecGetRGB()/WebPIDecGetYUVA() etc.
}
WebPIDelete(idec); // the object doesn't own the image memory, so it can
// now be deleted. config.output memory is preserved.
התמונה המפוענחת נמצאת עכשיו ב-config.output (או, במקום, config.output.u.RGBA במקרה הזה, כי מרחב הצבעים של הפלט המבוקש היה mode_BGRA). אפשר לשמור, להציג או לעבד את התמונה בדרך אחרת. לאחר מכן, אנחנו צריכים רק לדרוש מחדש את הזיכרון שהוקצה באובייקט התצורה. אפשר לקרוא לפונקציה הזו גם אם הזיכרון הוא חיצוני ולא הוקצה על ידי WebPDecode():
WebPFreeDecBuffer(&config.output);
באמצעות ה-API הזה, אפשר גם לפענח את התמונה לפורמט YUV ו-YUVA באמצעות MODE_YUV
ו-MODE_YUVA
בהתאמה. הפורמט הזה נקרא גם Y'CbCr.
ממשק API לקידוד פשוט
קיימות מספר פונקציות פשוטות מאוד לקידוד מערכי קידוד של דוגמאות RGBA ברוב הפריסות הנפוצות. הם מוצהרים בכותרת webp/encode.h
כך:
size_t WebPEncodeRGB(const uint8_t* rgb, int width, int height, int stride, float quality_factor, uint8_t** output);
size_t WebPEncodeBGR(const uint8_t* bgr, int width, int height, int stride, float quality_factor, uint8_t** output);
size_t WebPEncodeRGBA(const uint8_t* rgba, int width, int height, int stride, float quality_factor, uint8_t** output);
size_t WebPEncodeBGRA(const uint8_t* bgra, int width, int height, int stride, float quality_factor, uint8_t** output);
גורם האיכות quality_factor
נע בין 0 ל-100, ושולט בירידה ובאיכות במהלך הדחיסה. הערך 0 מייצג פלט באיכות נמוכה וגודל פלט קטן, ואילו 100 הוא הערך הגבוה ביותר וגודל הפלט הגדול ביותר.
כשהפעולה תושלם, הבייטים הדחוסים ימוקמו בנקודה *output
והגודל בבייטים מוחזר (אחרת מוחזר 0, במקרה של כשל). המתקשר צריך להתקשר ל-WebPFree()
בנקודה *output
כדי לפנות מקום בזיכרון.
מערך הקלט צריך להיות מערך דחוס של בייטים (אחד לכל ערוץ, בהתאם לשם הפונקציה). הערך stride
מייצג את מספר הבייטים שדרוש כדי לדלג משורה אחת לשורה הבאה. לדוגמה, פריסת BGRA היא:
יש פונקציות מקבילות לקידוד ללא אובדן נתונים, עם חתימות:
size_t WebPEncodeLosslessRGB(const uint8_t* rgb, int width, int height, int stride, uint8_t** output);
size_t WebPEncodeLosslessBGR(const uint8_t* bgr, int width, int height, int stride, uint8_t** output);
size_t WebPEncodeLosslessRGBA(const uint8_t* rgba, int width, int height, int stride, uint8_t** output);
size_t WebPEncodeLosslessBGRA(const uint8_t* bgra, int width, int height, int stride, uint8_t** output);
חשוב לזכור שהפונקציות האלה, כמו הגרסאות שאבדו, משתמשות בהגדרות ברירת המחדל של הספרייה. עבור ללא אובדן, המשמעות היא שהאפשרות 'מדויקת' מושבתת. ערכי RGB באזורים שקופים ישתנו כדי לשפר את הדחיסה. כדי למנוע זאת, צריך להשתמש ב-WebPEncode()
ולהגדיר את WebPConfig::exact
לערך 1
.
ממשק API לקידוד מתקדם
מתחת לפני השטח, המקודד כולל מספר רב של פרמטרים מתקדמים של קידוד.
הם יכולים לאזן בצורה טובה יותר את האיזון בין יעילות הדחיסה לבין זמן העיבוד.
הפרמטרים האלה נאספים בתוך המבנה WebPConfig
.
השדות בשימוש נפוץ במבנה הזה הם:
struct WebPConfig {
int lossless; // Lossless encoding (0=lossy(default), 1=lossless).
float quality; // between 0 and 100. For lossy, 0 gives the smallest
// size and 100 the largest. For lossless, this
// parameter is the amount of effort put into the
// compression: 0 is the fastest but gives larger
// files compared to the slowest, but best, 100.
int method; // quality/speed trade-off (0=fast, 6=slower-better)
WebPImageHint image_hint; // Hint for image type (lossless only for now).
// Parameters related to lossy compression only:
int target_size; // if non-zero, set the desired target size in bytes.
// Takes precedence over the 'compression' parameter.
float target_PSNR; // if non-zero, specifies the minimal distortion to
// try to achieve. Takes precedence over target_size.
int segments; // maximum number of segments to use, in [1..4]
int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum.
int filter_strength; // range: [0 = off .. 100 = strongest]
int filter_sharpness; // range: [0 = off .. 7 = least sharp]
int filter_type; // filtering type: 0 = simple, 1 = strong (only used
// if filter_strength > 0 or autofilter > 0)
int autofilter; // Auto adjust filter's strength [0 = off, 1 = on]
int alpha_compression; // Algorithm for encoding the alpha plane (0 = none,
// 1 = compressed with WebP lossless). Default is 1.
int alpha_filtering; // Predictive filtering method for alpha plane.
// 0: none, 1: fast, 2: best. Default if 1.
int alpha_quality; // Between 0 (smallest size) and 100 (lossless).
// Default is 100.
int pass; // number of entropy-analysis passes (in [1..10]).
int show_compressed; // if true, export the compressed picture back.
// In-loop filtering is not applied.
int preprocessing; // preprocessing filter (0=none, 1=segment-smooth)
int partitions; // log2(number of token partitions) in [0..3]
// Default is set to 0 for easier progressive decoding.
int partition_limit; // quality degradation allowed to fit the 512k limit on
// prediction modes coding (0: no degradation,
// 100: maximum possible degradation).
int use_sharp_yuv; // if needed, use sharp (and slow) RGB->YUV conversion
};
שימו לב שלרוב הפרמטרים האלה אפשר לערוך ניסויים באמצעות כלי שורת הפקודה cwebp
.
צריך לכלול את דוגמאות הקלט בתוך מבנה WebPPicture
.
במבנה הזה אפשר לאחסן דוגמאות קלט בפורמט RGBA או YUVA, בהתאם לערך של הדגל use_argb
.
המבנה מאורגן באופן הבא:
struct WebPPicture {
int use_argb; // To select between ARGB and YUVA input.
// YUV input, recommended for lossy compression.
// Used if use_argb = 0.
WebPEncCSP colorspace; // colorspace: should be YUVA420 or YUV420 for now (=Y'CbCr).
int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION)
uint8_t *y, *u, *v; // pointers to luma/chroma planes.
int y_stride, uv_stride; // luma/chroma strides.
uint8_t* a; // pointer to the alpha plane
int a_stride; // stride of the alpha plane
// Alternate ARGB input, recommended for lossless compression.
// Used if use_argb = 1.
uint32_t* argb; // Pointer to argb (32 bit) plane.
int argb_stride; // This is stride in pixels units, not bytes.
// Byte-emission hook, to store compressed bytes as they are ready.
WebPWriterFunction writer; // can be NULL
void* custom_ptr; // can be used by the writer.
// Error code for the latest error encountered during encoding
WebPEncodingError error_code;
};
למבנה הזה יש גם פונקציה שנועדה לפלוט את הבייטים הדחוסים כשהם הופכים לזמינים. למטה מופיעה דוגמה עם הרשאת כתיבה בזיכרון.
כותבים אחרים יכולים לאחסן נתונים ישירות בקובץ (ראו דוגמה כזו ב-examples/cwebp.c
).
התהליך הכללי לקידוד באמצעות ה-API המתקדם נראה כך:
תחילה עלינו להגדיר תצורת קידוד שמכילה את הפרמטרים של הדחיסה. שימו לב שאפשר להשתמש באותה תצורה כדי לדחוס כמה תמונות שונות אחר כך.
#include "webp/encode.h"
WebPConfig config;
if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality_factor)) return 0; // version error
// Add additional tuning:
config.sns_strength = 90;
config.filter_sharpness = 6;
config.alpha_quality = 90;
config_error = WebPValidateConfig(&config); // will verify parameter ranges (always a good habit)
לאחר מכן, יש להפנות לדגימות הקלט אל WebPPicture
באמצעות הפניה או עותק. בהמשך מוצגת דוגמה להקצאת המאגר להחזקת הדגימות. אבל אפשר להגדיר בקלות 'view' למערך לדוגמה שכבר הוקצה. פרטים נוספים זמינים בפונקציה WebPPictureView()
.
// Setup the input data, allocating a picture of width x height dimension
WebPPicture pic;
if (!WebPPictureInit(&pic)) return 0; // version error
pic.width = width;
pic.height = height;
if (!WebPPictureAlloc(&pic)) return 0; // memory error
// At this point, 'pic' has been initialized as a container, and can receive the YUVA or RGBA samples.
// Alternatively, one could use ready-made import functions like WebPPictureImportRGBA(), which will take
// care of memory allocation. In any case, past this point, one will have to call WebPPictureFree(&pic)
// to reclaim allocated memory.
כדי לפלוט את הבייטים הדחוסים, מתבצעת קריאה לפעולה (hook) בכל פעם שיש בייטים חדשים זמינים. הנה דוגמה פשוטה עם כותב הזיכרון שהוצהר ב-webp/encode.h
. סביר להניח שתצטרכו את האתחול הזה כדי לדחוס כל תמונה:
// Set up a byte-writing method (write-to-memory, in this case):
WebPMemoryWriter writer;
WebPMemoryWriterInit(&writer);
pic.writer = WebPMemoryWrite;
pic.custom_ptr = &writer;
עכשיו אנחנו מוכנים לדחוס את דגימות הקלט (ולשחרר את הזיכרון שלהן לאחר מכן):
int ok = WebPEncode(&config, &pic);
WebPPictureFree(&pic); // Always free the memory associated with the input.
if (!ok) {
printf("Encoding error: %d\n", pic.error_code);
} else {
printf("Output size: %d\n", writer.size);
}
לשימוש מתקדם יותר ב-API ובמבנה, מומלץ לעיין במסמכי התיעוד שזמינים בכותרת webp/encode.h
.
קריאת הקוד לדוגמה examples/cwebp.c
יכולה לעזור לכם למצוא פרמטרים שפחות בשימוש.