public
Last active

Binary Image Exchange Format Proposal

  • Download Gist
ReferenceImpl.BinaryImage.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
/*
* Binary Image Exchange Format reference implementation.
*
* Note that not everything here has been exhaustively tested. There may be
* bugs a-lurkin'.
*
* This implementation is written to conform to version 1.0.3 of the BIEF spec.
*
* Latest version:
* https://gist.github.com/2585085
*
* Authors:
* Daniel Keep <daniel.keep@gmail.com>.
*
* History:
* v1.1: Christened format "BIEF". Changed to big-endian by default.
* ReadImage now detects non-BIEF files and reads them as big-endian
* raw files instead.
* v1.0: First release.
*/
/*
* Copyright (c) 2012 Daniel Keep.
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
 
// NuGet Package: DotNetZip
using Ionic.Zlib;
 
namespace Dk.x10c
{
/// <summary>
/// This class has methods for reading and writing BIEF
/// format files, as specified by <https://gist.github.com/2585085>.
/// </summary>
public static class BinaryImage
{
/// <summary>
/// Reads a binary image. Note that this method will work on both
/// actual BIEF-formatted files and raw big-endian files.
/// </summary>
/// <param name="path">Path to the binary image file.</param>
/// <param name="headers">If non-null, all headers will be
/// added to this dictionary. Header keys will be lower case.</param>
/// <returns>The decoded image data.</returns>
public static ushort[] ReadImage(string path, Dictionary<string, string> headers = null)
{
using (var fs = new FileStream(path, FileMode.Open))
return ReadImage(fs, headers);
}
 
/// <summary>
/// Reads a binary image. Note that this method will work on both
/// actual BIEF-formatted files and raw big-endian files.
/// </summary>
/// <param name="s">Stream to read from. The stream must be seekable.</param>
/// <param name="headers">If non-null, all headers will be
/// added to this dictionary. Header keys will be lower case.</param>
/// <returns>The decoded image data.</returns>
public static ushort[] ReadImage(Stream s, Dictionary<string, string> headers = null)
{
// Defaults as per spec
var byteOrder = ByteOrder.BigEndian;
var compress = Compression.None;
var encoding = Encoding.None;
var payLength = -1;
 
// Mark current position
var headerStart = s.Seek(0, SeekOrigin.Current);
 
// Parse headers
var tr = new StreamReader(s, System.Text.Encoding.UTF8);
{
string line = tr.ReadLine();
{
var parts = line.Split(verSep, 2, StringSplitOptions.None);
 
if (parts.Length == 2 && parts[0] == "BIEF")
{
// Only version 0.1 supported.
if (parts[1] != "0.1")
throw new Exception("Unsupported version of BIEF: " + parts[1]);
}
else
{
// Ok, this means the file isn't BIEF. Try to read
// as big-endian, uncompressed raw.
s.Seek(headerStart, SeekOrigin.Begin);
return ReadRawImage(s);
}
}
 
while ((line = tr.ReadLine()) != null)
{
line = line.Trim();
if (line.Length == 0)
// No more headers!
break;
 
var parts = line.Split(headerSep, 2, StringSplitOptions.None);
 
// We ignore lines not of the form "key: value".
if (parts.Length == 2)
{
var key = parts[0].Trim().ToLower();
var val = parts[1].Trim();
 
// Note that this includes standard headers, since users
// might be curious.
if (headers != null)
headers.Add(key, val);
 
switch (key)
{
case "byte-order":
switch (val.ToLower())
{
case "big-endian":
byteOrder = ByteOrder.BigEndian;
break;
 
case "little-endian":
byteOrder = ByteOrder.LittleEndian;
break;
}
break;
 
case "compression":
switch (val.ToLower())
{
case "none":
compress = Compression.None;
break;
 
case "zlib":
compress = Compression.Zlib;
break;
}
break;
 
case "encoding":
switch (val.ToLower())
{
case "none":
encoding = Encoding.None;
break;
 
case "base64":
encoding = Encoding.Base64;
break;
}
break;
 
case "payload-length":
if (!int.TryParse(val, out payLength))
payLength = -1;
break;
}
}
}
}
 
// Locate end of headers.
/*
* This is nasty because StreamReader doesn't deign to tell us
* how many bytes its consumed and it buffers. This means that
* once we've read the headers, we don't *actually* know where in
* the file we're supposed to be.
*
* Outside of re-writing the header parsing code to avoid the use
* of StreamReader entirely (*effort*), this is the next-best
* solution I could think of.
*
* All we do is scan the stream, looking for two consecutive new
* lines. gotEol is initialised to true so that if the first
* thing we see is a newline (i.e. no headers at all), we take
* that as the end of the headers.
*/
s.Seek(headerStart, SeekOrigin.Begin);
long dataStart = 0;
{
int b;
bool gotEol = true,
gotCr = false;
while ((b = s.ReadByte()) >= 0)
{
var c = (char)b;
if (gotCr)
{
gotCr = false;
if (c == '\n')
{
if (gotEol)
break;
gotEol = true;
}
else
gotEol = false;
}
else if (b == '\n')
{
if (gotEol)
break;
gotEol = true;
}
else if (b == '\r')
{
gotCr = true;
}
else
gotEol = false;
}
 
dataStart = s.Seek(0, SeekOrigin.Current);
}
 
// Compute payload length if not specified.
if (payLength < 0)
{
payLength = (int)(s.Seek(0, SeekOrigin.End) - dataStart);
s.Seek(dataStart, SeekOrigin.Begin);
}
 
// Ensure we're at the start of the payload
s.Seek(dataStart, SeekOrigin.Begin);
 
// Read in the (potentially) encoded data
var ebytes = new byte[payLength];
s.Read(ebytes, 0, payLength);
 
// Handle decoding to (potentially) compressed bytes.
byte[] cbytes;
switch (encoding)
{
case Encoding.None:
cbytes = ebytes;
break;
 
case Encoding.Base64:
{
var str = System.Text.Encoding.UTF8.GetString(ebytes);
cbytes = Convert.FromBase64String(str);
}
break;
 
default:
throw new NotImplementedException("unknown encoding");
}
 
// Handle decompressing to bytes.
byte[] bytes;
switch (compress)
{
case Compression.None:
bytes = cbytes;
break;
 
case Compression.Zlib:
bytes = zlibDecompress(cbytes);
break;
 
default:
throw new NotImplementedException("unknown compression");
}
 
// Ensure we have complete words.
if ((bytes.Length & 1) == 1)
throw new InvalidDataException("malformed binary image: last word is incomplete");
 
// Convert to words.
var words = new ushort[bytes.Length >> 1];
{
int lb, hb;
switch (byteOrder)
{
case ByteOrder.BigEndian:
hb = 0;
lb = 1;
break;
 
case ByteOrder.LittleEndian:
lb = 0;
hb = 1;
break;
 
default:
// What, seriously?!
throw new NotImplementedException("unknown byte order");
}
 
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
words[i] = (ushort)(bytes[j + lb] | (bytes[j + hb] << 8));
}
}
 
return words;
}
 
/// <summary>
/// Writes data to a binary image.
/// </summary>
/// <param name="path">Path of the file to write to.</param>
/// <param name="words">The data to write.</param>
/// <param name="headers">Additional headers to include in the output.</param>
/// <param name="compression">Compression scheme to use.</param>
/// <param name="encoding">Byte encoding scheme to use.</param>
/// <param name="byteOrder">On-disk byte ordering.</param>
public static void WriteImage(string path,
ushort[] words,
Dictionary<string, string> headers = null,
Compression compression = Compression.Zlib,
Encoding encoding = Encoding.Base64,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Create))
WriteImage(fs, words, headers, compression, encoding, byteOrder);
}
 
/// <summary>
/// Writes data to a binary image.
/// </summary>
/// <param name="s">Stream to write to.</param>
/// <param name="words">The data to write.</param>
/// <param name="headers">Additional headers to include in the output.</param>
/// <param name="compression">Compression scheme to use.</param>
/// <param name="encoding">Byte encoding scheme to use.</param>
/// <param name="byteOrder">On-disk byte ordering.</param>
public static void WriteImage(
Stream s,
ushort[] words,
Dictionary<string, string> headers = null,
Compression compression = Compression.Zlib,
Encoding encoding = Encoding.Base64,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
// What will eventually contain our encoded bytes.
byte[] ebytes;
 
// Write out headers.
/* NOTE: we can't dispose this since it also disposes the
* underlying stream. How *thoughtful*.
*/
var tw = new StreamWriter(s, System.Text.Encoding.ASCII);
{
tw.NewLine = "\r\n";
 
tw.WriteLine("BIEF/0.1");
 
// Write out extra headers. If these include standard headers,
// it won't matter because we'll supercede them.
if (headers != null)
foreach (var kv in headers)
tw.WriteLine("{0}: {1}", kv.Key, kv.Value);
 
int lb, hb;
switch (byteOrder)
{
case ByteOrder.BigEndian:
// Don't output an explicit header for this case.
//tw.WriteLine("Byte-Order: Big-Endian");
hb = 0;
lb = 1;
break;
 
case ByteOrder.LittleEndian:
tw.WriteLine("Byte-Order: Little-Endian");
lb = 0;
hb = 1;
break;
 
default:
// WAT.
throw new NotImplementedException("unknown byte order");
}
 
// Convert words into byte-ordered bytes.
var bytes = new byte[2 * words.Length];
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
bytes[j + lb] = (byte)words[i];
bytes[j + hb] = (byte)(words[i] >> 8);
}
 
// Compress
byte[] cbytes;
switch (compression)
{
case Compression.None:
// Default
//tw.WriteLine("Compression: None");
cbytes = bytes;
break;
 
case Compression.Zlib:
tw.WriteLine("Compression: Zlib");
cbytes = zlibCompress(bytes);
break;
 
default:
throw new NotImplementedException("unknown compression");
}
 
// Encode
switch (encoding)
{
case Encoding.None:
// Default.
//tw.WriteLine("Encoding: None");
ebytes = cbytes;
break;
 
case Encoding.Base64:
tw.WriteLine("Encoding: Base64");
{
var str = Convert.ToBase64String(cbytes, Base64FormattingOptions.InsertLineBreaks);
ebytes = System.Text.Encoding.ASCII.GetBytes(str);
}
break;
 
default:
throw new NotImplementedException("unknown encoding");
}
 
// Output payload-length header.
tw.WriteLine("Payload-Length: {0}", ebytes.Length);
 
// Terminate headers
tw.WriteLine();
tw.Flush();
}
 
// Write encoded bytes out; and we're done!
s.Write(ebytes, 0, ebytes.Length);
}
 
/// <summary>
/// Reads a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="path">Path to the file to read from.</param>
/// <param name="byteOrder">Byte order of the file.</param>
/// <returns>The contents of the file.</returns>
public static ushort[] ReadRawImage(
string path,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Open))
return ReadRawImage(fs, byteOrder);
}
 
/// <summary>
/// Reads a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="s">Stream to read from.</param>
/// <param name="byteOrder">Byte order of the file.</param>
/// <returns>The contents of the file.</returns>
public static ushort[] ReadRawImage(
Stream s,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
var start = s.Seek(0, SeekOrigin.Current);
var end = s.Seek(0, SeekOrigin.End);
s.Seek(start, SeekOrigin.Begin);
 
var length = (int)(end - start);
 
if ((length & 1) == 1)
throw new InvalidDataException("malformed binary image: last word is incomplete");
 
var bytes = new byte[length];
s.Read(bytes, 0, length);
var words = new ushort[length >> 1];
 
int lb, hb;
if (byteOrder == ByteOrder.LittleEndian)
{
lb = 0;
hb = 1;
}
else
{
hb = 0;
lb = 1;
}
 
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
words[i] = (ushort)(bytes[j + lb] | (bytes[j + hb] << 8));
}
 
return words;
}
 
/// <summary>
/// Writes a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="path">Path to the file to write to.</param>
/// <param name="words">Data to write.</param>
/// <param name="byteOrder">Byte order of the file.</param>
public static void WriteRawImage(
string path,
ushort[] words,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Create))
WriteRawImage(fs, words, byteOrder);
}
 
/// <summary>
/// Writes a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="s">Stream to write to.</param>
/// <param name="words">Data to write.</param>
/// <param name="byteOrder">Byte order of the file.</param>
public static void WriteRawImage(
Stream s,
ushort[] words,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
var bytes = new byte[words.Length << 1];
 
int lb, hb;
if (byteOrder == ByteOrder.LittleEndian)
{
lb = 0;
hb = 1;
}
else
{
hb = 0;
lb = 1;
}
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
bytes[j + lb] = (byte)words[i];
bytes[j + hb] = (byte)(words[i] >> 8);
}
 
s.Write(bytes, 0, bytes.Length);
}
 
private static byte[] zlibCompress(byte[] bytes)
{
return ZlibStream.CompressBuffer(bytes);
}
 
private static byte[] zlibDecompress(byte[] cbytes)
{
return ZlibStream.UncompressBuffer(cbytes);
}
 
static BinaryImage()
{
verSep = new char[] { '/' };
headerSep = new char[] { ':' };
}
 
private static readonly char[] verSep;
private static readonly char[] headerSep;
}
public enum ByteOrder
{
BigEndian,
LittleEndian,
}
 
public enum Encoding
{
None,
Base64,
}
 
public enum Compression
{
None,
Zlib,
}
}
bief-proposal.rst
reStructuredText

Binary Image Exchange Format Proposal

Author: Daniel Keep <daniel.keep@gmail.com>
Version: 1.0.3
Licence: http://creativecommons.org/publicdomain/zero/1.0/
Discussion: http://www.reddit.com/r/dcpu16/comments/t4xy2/

Recently, I've been working on some tools for creating disk images and formatting said images with a filesystem. At the same time, there have been a number of people on Reddit asking about what byte order their tools should be producing or consuming. It's also occurred to me that DCPU is a bit unusual among emulated platforms in that some of the most prominent emulators right from the get-go are actually web apps that users copy+paste programs into.

When I wrote up my floppy drive spec, I wanted to include a sample program with a corresponding disk image. Sadly, I couldn't attach a binary file, only text. It occurrs to me that web-based emulators could very well have similar problems.

So, rather than get ahead of myself, I'd like to make a proposal and see how the community responds. Specifically, I'm looking for the opinions of tool writers.

The idea

I'm proposing that we define a very simple encapsulation format to be used for storing and exchanging binary files of various types. Specifically, binary dumps (or images) of data comprised of 16-bit words for the DCPU-16, representing data such as machine code, ROM and disk images.

As an example, here is an image of a 1.44 MB disk formatted with zeroes and the LE-packed string "Hello, World!" stored at the beginning:

BIEF/0.1
Type: Floppy
Access: Read-Write
Compression: Zlib
Encoding: Base64
Payload-Length: 2010

eNrtwTENACAMALBJgR8hOMAAfEuW4P/ABGfbMzNHrXZrZ/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPnq4MQRq

In addition to the basic encapsulation headers (Byte-Order, Compression, Encoding and Content-Length) it also allows for special-purpose headers to be added (Access and Type).

Benefits and drawbacks

Things this format will give us:

  • A common format for binary image interchange that also specifies byte order.
  • A format with built-in compression, making internet transmission quicker.
  • A format which can be stored as plain text, suitable for submission to web apps and paste bins without risk of corruption.
  • A format which should be trivially readable in just about every programming language in the world [1].

Drawbacks:

  • Not as simple to read as an uncompressed, unencoded fixed byte order image.
  • Necessarily larger if files are stored without compression.

Open questions

  • Is it worth having a little-endian mode at all? It's still in the reference implementation, but I've removed it from the spec because I just can't come up with a logically sound reason for having it.
  • Is Content-Length worth having, or just throw it away. It feels a bit like a security blanket: makes you feel better but doesn't really do anything.

Specifics

No file extension is specified or required.

Each conforming file begins with the format identifier. This is the five characters "BIEF/" followed by a version identifier and terminated by a single newline. The version number described in this proposal is "0.1"; it will be changed to "1.0" in the event the format is accepted by the community.

Newlines may be either a single linefeed (0x0a) byte or a carriage-return, linefeed (0x0d, 0x0a) byte sequence. Newlines should be written out as a carriage-return, lifefeed sequence where possible [4].

This is followed by a sequence of zero or more headers. Each header is made up of a key, followed by a colon (':'), followed by the value and finally terminated by a newline character. Unless there is a compelling reason to do so, keys and values should both the case insensitive. Whitespace around the key and value should be ignored. Headers should be written in 7-bit ASCII, but read in as UTF-8 if possible [2].

Malformed or unrecognised headers should be ignored. It is entirely possible for the file to contain no headers at all. In the case of duplicate headers, the last value for a given header is used.

The headers are terminated by a zero-length line; that is, two consecutive newlines. If a file contains no headers, then it will start with a newline.

At this point, the rest of the file is the actual payload (or data) of the file. The file should not contain any trailing bytes.

General headers

Byte-Order

Deprecated. This header is no longer a part of the base format. It will remain documented, however, until the format is accepted and finalised.

"Big-Endian" or "Little-Endian", default if not specified is big-endian.

Producing programs should endeavour to output files using big-endian by default.

Encoding

"None" or "Base64", default if not specified is None.

Producing programs should endeavour to output files using Base64 by default.

The use of base64 allows for images to be passed around on the internet more easily: they can be put into gists or uploaded to pastebins. This also avoids any potential problems with languages that represent binary data as Unicode or encoded 8-bit strings (like Javascript), and languages without 8-bit safe strings (which I believe Lua is an example of).

Compression

"None" or "Zlib", default if not specified is None.

Producing programs should endeavour to output files using Zlib by default.

Compression means a 1.44 MB disk image starting with "Hello, World!" is just over 2 KB instead of 1.44 MB.

zlib was chosen thanks to its near total ubiquity. Specifically, it means a deflate-compressed stream with the zlib header, not a raw deflate stream as Microsoft seems to love to use [3].

Payload-Length

The value is a decimal integer representing the number of compressed, encoded bytes in the payload.

Producing programs should include a Payload-Length header, consuming programs should ideally be prepared to operate without one.

This header is included largely as a hedge against pastebins tacking on an errant newline here or there in the face of a particularly inflexible base64 implementation.

Disk image headers

This section is just normative; that is, I'm not attempting to standardise this stuff, just giving a little extra context on what I'm personally using this for.

Type
Specifies the type of media the image represents. Currently, I'm only using "Floppy", although I can see "Tape" and "Hard-Disk" being used in the future.
Access
"Read-Write" or "Read-Only". Used to implement the write-lock switch on the old 3.5" floppy.

Changelog

1.0.3

Changed proposal to be conforming reST. Added identification line. The major impetus for this was to allow the reference implementation to automatically fall back to raw mode if the line isn't present.

Changed byte-order default to big-endian then proceeded to remove it from the spec entirely. Most people seem to have settled on big-endian already, as much as I think that's a completely silly choice. As Harold Lam would say: I'm a big enough man to admit when you're all bloody wrong. :P

1.0.2

Added license. Added language on default newline format for output. Clarified behaviour on reading duplicate headers. Added changelog. Added link back to Reddit discussion thread.

Clarified that this is for memory images, not bitmap images.

Renamed "Content-Length" to "Payload-Length"; kudos to cheese_magnet.

1.0.1
Fixed a mistake in the example disk image.
1.0.0
Initial release.

License

Licensed under the CC0 license: http://creativecommons.org/publicdomain/zero/1.0/

To the extent possible under law, the author has waived all copyright and related or neighboring rights to "Binary Image Exchange Format Proposal". This work is published from: Australia.

[1] Show me a language without good line-reading IO routines in its standard library, and I'll show you a rubbish language. ;)
[2] This is the "generous on input, strict on output" principle.
[3] Incidentally, don't use System.IO.Compression.DeflateStream. It's complete garbage.
[4] This has been chosen because the most common text editor in the world is, probably (and unfortunately), Microsoft Notepad. Notepad is also just about the only text editor left that refuses to recognise single linefeeds as newlines. In this way, BIEF files opened in Notepad will not look "broken" to lay people.

This is not shit.

jonpovey: I try :)

any chances of creating creating a tool to convert disks from compressed to uncompressed?

i've been trying to get devkit to use uncompressed disks by changing the default settings in read and write image, doesn't work though.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.