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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
|
/*
*
* Copyright (C) 2003-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Joerg Riesmeier
*
* Purpose: Convert XML document to DICOM file or data set
*
* Last Update: $Author: uli $
* Update Date: $Date: 2010-12-15 13:59:57 $
* CVS/RCS Revision: $Revision: 1.34 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dctk.h"
#include "dcmtk/dcmdata/dcpxitem.h" /* for class DcmPixelItem */
#include "dcmtk/dcmdata/cmdlnarg.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofconapp.h"
#include "dcmtk/dcmdata/dcostrmz.h" /* for dcmZlibCompressionLevel */
#define INCLUDE_CSTDARG
#include "dcmtk/ofstd/ofstdinc.h"
#ifdef WITH_ZLIB
#include <zlib.h> /* for zlibVersion() */
#endif
#define OFFIS_CONSOLE_APPLICATION "xml2dcm"
#define OFFIS_CONSOLE_DESCRIPTION "Convert XML document to DICOM file or data set"
// currently not used since DTD is always retrieved from XML document
//#define DOCUMENT_TYPE_DEFINITION_FILE "dcm2xml.dtd"
static OFLogger xml2dcmLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION);
static OFLogger xmlLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION ".libxml");
static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v"
OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $";
// ********************************************
#ifdef WITH_LIBXML
#include <libxml/parser.h>
// stores pointer to character encoding handler
static xmlCharEncodingHandlerPtr EncodingHandler = NULL;
// This function is also used in dcmsr, try to stay in sync!
extern "C" void errorFunction(void * ctx, const char *msg, ...)
{
OFString &buffer = *OFstatic_cast(OFString*, ctx);
if (!xmlLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
return;
#if defined(HAVE_VSNPRINTF) && defined(HAVE_PROTOTYPE_VSNPRINTF)
// libxml calls us multiple times for one line of log output which would
// result in garbled output. To avoid this, we buffer the output in a local
// string in the caller which we get through our 'ctx' parameter. Then, we
// output this string on one go when we receive a newline.
va_list ap;
char buf[1024];
va_start(ap, msg);
#ifdef HAVE_PROTOTYPE_STD__VSNPRINTF
std::vsnprintf(buf, 1024, msg, ap);
#else
vsnprintf(buf, 1024, msg, ap);
#endif
va_end(ap);
// Since we can't do anything about a too small buffer for vsnprintf(), we
// ignore it. But we do make sure the buffer is null-terminated!
buf[1023] = '\0';
buffer += buf;
// If there is a full line in the buffer...
size_t pos = buffer.find('\n');
while (pos != OFString_npos)
{
// ..output it and remove it from the buffer
OFLOG_DEBUG(xmlLogger, buffer.substr(0, pos));
buffer.erase(0, pos + 1);
pos = buffer.find('\n');
}
#elif defined(HAVE_VPRINTF)
// No vsnprint, but at least vfprintf. Output the messages directly to stderr.
va_list ap;
va_start(ap, msg);
#ifdef HAVE_PROTOTYPE_STD__VFPRINTF
std::vfprintf(stderr, msg, ap);
#else
vfprintf(stderr, msg, ap);
#endif
va_end(ap);
#else
// We can only show the most basic part of the message, this will look bad :(
printf("%s", msg);
#endif
#ifndef HAVE_VSNPRINTF
// Only the vsnprintf() branch above uses 'buffer' which means the compiler
// would warn about an unused variable if HAVE_VSNPRINTF is undefined.
buffer += "";
#endif
}
static OFBool convertUtf8ToCharset(const xmlChar *fromString,
OFString &toString)
{
OFBool result = OFFalse;
if (EncodingHandler != NULL)
{
/* prepare input/output buffers */
xmlBufferPtr fromBuffer = xmlBufferCreate();
xmlBufferPtr toBuffer = xmlBufferCreate();
xmlBufferCat(fromBuffer, fromString);
/* convert character encoding of given string */
result = (xmlCharEncOutFunc(EncodingHandler, toBuffer, fromBuffer) >= 0);
if (result)
toString = OFreinterpret_cast(const char *, xmlBufferContent(toBuffer));
/* free allocated memory */
xmlBufferFree(toBuffer);
xmlBufferFree(fromBuffer);
}
return result;
}
static OFCondition checkNode(xmlNodePtr current,
const char *name)
{
OFCondition result = EC_Normal;
/* check whether node is valid at all */
if (current != NULL)
{
/* check whether node has expected name */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, name)) != 0)
{
OFLOG_ERROR(xml2dcmLogger, "document of the wrong type, was '" << current->name << "', '" << name << "' expected");
result = EC_IllegalCall;
}
} else {
OFLOG_ERROR(xml2dcmLogger, "document of the wrong type, '" << name << "' expected");
result = EC_IllegalCall;
}
return result;
}
static OFCondition createNewElement(xmlNodePtr current,
DcmElement *&newElem)
{
OFCondition result = EC_IllegalCall;
/* check whether node is valid */
if (current != NULL)
{
/* get required information from XML element */
xmlChar *elemTag = xmlGetProp(current, OFreinterpret_cast(const xmlChar *, "tag"));
xmlChar *elemVR = xmlGetProp(current, OFreinterpret_cast(const xmlChar *, "vr"));
/* convert tag string */
DcmTagKey dcmTagKey;
unsigned int group = 0xffff;
unsigned int elem = 0xffff;
if (sscanf(OFreinterpret_cast(char *, elemTag), "%x,%x", &group, &elem ) == 2)
{
dcmTagKey.set(group, elem);
DcmTag dcmTag(dcmTagKey);
/* convert vr string */
DcmVR dcmVR(OFreinterpret_cast(char *, elemVR));
DcmEVR dcmEVR = dcmVR.getEVR();
if (dcmEVR == EVR_UNKNOWN)
{
OFLOG_WARN(xml2dcmLogger, "invalid 'vr' attribute (" << elemVR
<< ") for " << dcmTag << ", using unknown VR");
}
/* check for correct vr */
const DcmEVR tagEVR = dcmTag.getEVR();
if ((tagEVR != dcmEVR) && (dcmEVR != EVR_UNKNOWN) && (tagEVR != EVR_UNKNOWN) &&
((dcmTagKey != DCM_LUTData) || ((dcmEVR != EVR_US) && (dcmEVR != EVR_SS) && (dcmEVR != EVR_OW))) &&
((tagEVR != EVR_xs) || ((dcmEVR != EVR_US) && (dcmEVR != EVR_SS))) &&
((tagEVR != EVR_ox) || ((dcmEVR != EVR_OB) && (dcmEVR != EVR_OW))))
{
OFLOG_WARN(xml2dcmLogger, "tag " << dcmTag << " has wrong VR (" << dcmVR.getVRName()
<< "), correct is " << dcmTag.getVR().getVRName());
}
if (dcmEVR != EVR_UNKNOWN)
dcmTag.setVR(dcmVR);
/* create DICOM element */
result = newDicomElement(newElem, dcmTag);
} else {
OFLOG_WARN(xml2dcmLogger, "invalid 'tag' attribute (" << elemTag << "), ignoring node");
result = EC_InvalidTag;
}
if (result.bad())
{
/* delete new element if an error occured */
delete newElem;
newElem = NULL;
}
/* free allocated memory */
xmlFree(elemTag);
xmlFree(elemVR);
}
return result;
}
static OFCondition putElementContent(xmlNodePtr current,
DcmElement *element)
{
OFCondition result = EC_IllegalCall;
/* check whether node and element are valid */
if ((current != NULL) && (element != NULL))
{
DcmEVR dcmEVR = element->getVR();
/* get the XML node content */
xmlChar *elemVal = xmlNodeGetContent(current);
xmlChar *attrVal = xmlGetProp(current, OFreinterpret_cast(const xmlChar *, "binary"));
/* check whether node content is present */
if (xmlStrcmp(attrVal, OFreinterpret_cast(const xmlChar *, "hidden")) == 0)
OFLOG_WARN(xml2dcmLogger, "content of node " << element->getTag() << " is 'hidden', empty element inserted");
/* check whether node content is base64 encoded */
else if (xmlStrcmp(attrVal, OFreinterpret_cast(const xmlChar *, "base64")) == 0)
{
Uint8 *data = NULL;
const size_t length = OFStandard::decodeBase64(OFreinterpret_cast(char *, elemVal), data);
if (length > 0)
{
if (dcmEVR == EVR_OW)
{
/* Base64 decoder produces big endian output data, convert to local byte order */
swapIfNecessary(gLocalByteOrder, EBO_BigEndian, data, length, sizeof(Uint16));
}
result = element->putUint8Array(data, length);
/* delete buffer since data is copied into the element */
delete[] data;
}
}
/* check whether node content is stored in a file */
else if (xmlStrcmp(attrVal, OFreinterpret_cast(const xmlChar *, "file")) == 0)
{
if (xmlStrlen(elemVal) > 0)
{
const char *filename = OFreinterpret_cast(char *, elemVal);
/* try to open binary file */
FILE *f = fopen(filename, "rb");
if (f != NULL)
{
/* determine filesize */
const size_t fileSize = OFStandard::getFileSize(filename);
unsigned long buflen = fileSize;
/* if odd then make even (DICOM requires even length values) */
if (buflen & 1)
buflen++;
Uint8 *buf = NULL;
/* create buffer of OB or OW data */
if (dcmEVR == EVR_OW)
{
Uint16 *buf16 = NULL;
result = element->createUint16Array(buflen / 2, buf16);
buf = OFreinterpret_cast(Uint8 *, buf16);
} else
result = element->createUint8Array(buflen, buf);
if (result.good())
{
/* read binary file into the buffer */
if (fread(buf, 1, OFstatic_cast(size_t, fileSize), f) != fileSize)
{
char errBuf[256];
const char *text = OFStandard::strerror(errno, errBuf, sizeof(errBuf));
if (text == NULL) text = "(unknown error code)";
OFLOG_ERROR(xml2dcmLogger, "error reading binary data file: " << filename << ": " << text);
result = EC_CorruptedData;
}
else if (dcmEVR == EVR_OW)
{
/* swap 16 bit OW data (if necessary) */
swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, buf, buflen, sizeof(Uint16));
}
}
fclose(f);
} else {
OFLOG_ERROR(xml2dcmLogger, "cannot open binary data file: " << filename);
result = EC_InvalidTag;
}
} else
OFLOG_ERROR(xml2dcmLogger, "filename for element " << element->getTag() << " is missing, empty element inserted");
} else {
OFString dicomVal;
/* convert character set from UTF8 (for specific VRs only) */
if (((dcmEVR == EVR_PN) || (dcmEVR == EVR_SH) || (dcmEVR == EVR_LO) ||
(dcmEVR == EVR_ST) || (dcmEVR == EVR_LT) || (dcmEVR == EVR_UT)) &&
(xmlStrlen(elemVal) > 0) && convertUtf8ToCharset(elemVal, dicomVal))
{
result = element->putString(dicomVal.c_str());
} else {
/* set the value of the newly created element */
result = element->putString(OFreinterpret_cast(char *, elemVal));
}
}
/* free allocated memory */
xmlFree(elemVal);
xmlFree(attrVal);
}
return result;
}
static OFCondition parseElement(DcmItem *dataset,
xmlNodePtr current)
{
DcmElement *newElem = NULL;
/* create new DICOM element from XML element */
OFCondition result = createNewElement(current, newElem);
if (result.good())
{
/* retrieve specific character set (only on main dataset level) */
if ((EncodingHandler == NULL) && (dataset->ident() == EVR_dataset) &&
(newElem->getTag() == DCM_SpecificCharacterSet))
{
const char *encString = NULL;
xmlChar *elemVal = xmlNodeGetContent(current);
/* check for known character set */
if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 6")) == 0)
encString = "UTF-8";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 192")) == 0)
encString = "UTF-8";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 100")) == 0)
encString = "ISO-8859-1";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 101")) == 0)
encString = "ISO-8859-2";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 109")) == 0)
encString = "ISO-8859-3";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 110")) == 0)
encString = "ISO-8859-4";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 148")) == 0)
encString = "ISO-8859-9";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 144")) == 0)
encString = "ISO-8859-5";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 127")) == 0)
encString = "ISO-8859-6";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 126")) == 0)
encString = "ISO-8859-7";
else if (xmlStrcmp(elemVal, OFreinterpret_cast(const xmlChar *, "ISO_IR 138")) == 0)
encString = "ISO-8859-8";
else if (xmlStrlen(elemVal) > 0)
OFLOG_ERROR(xml2dcmLogger, "character set '" << elemVal << "' not supported");
if (encString != NULL)
{
/* find appropriate encoding handler */
EncodingHandler = xmlFindCharEncodingHandler(encString);
}
xmlFree(elemVal);
}
/* set the element value */
result = putElementContent(current, newElem);
/* insert the new element into the dataset */
if (result.good())
result = dataset->insert(newElem, OFTrue /*replaceOld*/);
if (result.bad())
{
/* delete element if insertion or putting the value failed */
delete newElem;
}
}
return result;
}
// forward declaration
static OFCondition parseDataSet(DcmItem *dataset,
xmlNodePtr current,
E_TransferSyntax xfer);
static OFCondition parseSequence(DcmSequenceOfItems *sequence,
xmlNodePtr current,
E_TransferSyntax xfer)
{
OFCondition result = EC_IllegalCall;
if (sequence != NULL)
{
/* ignore blank (empty or whitespace only) nodes */
while ((current != NULL) && xmlIsBlankNode(current))
current = current->next;
while (current != NULL)
{
/* ignore non-item nodes */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "item")) == 0)
{
/* create new sequence item */
DcmItem *newItem = new DcmItem();
if (newItem != NULL)
{
sequence->insert(newItem);
/* proceed parsing the item content */
parseDataSet(newItem, current->xmlChildrenNode, xfer);
}
} else if (!xmlIsBlankNode(current))
OFLOG_WARN(xml2dcmLogger, "unexpected node '" << current->name << "', 'item' expected, skipping");
/* proceed with next node */
current = current->next;
}
result = EC_Normal;
}
return result;
}
static OFCondition parsePixelSequence(DcmPixelSequence *sequence,
xmlNodePtr current)
{
OFCondition result = EC_IllegalCall;
if (sequence != NULL)
{
/* ignore blank (empty or whitespace only) nodes */
while ((current != NULL) && xmlIsBlankNode(current))
current = current->next;
while (current != NULL)
{
/* ignore non-pixel-item nodes */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "pixel-item")) == 0)
{
/* create new pixel item */
DcmPixelItem *newItem = new DcmPixelItem(DcmTag(DCM_Item, EVR_OB));
if (newItem != NULL)
{
sequence->insert(newItem);
/* put pixel data into the item */
putElementContent(current, newItem);
}
} else if (!xmlIsBlankNode(current))
OFLOG_WARN(xml2dcmLogger, "unexpected node '" << current->name << "', 'pixel-item' expected, skipping");
/* proceed with next node */
current = current->next;
}
result = EC_Normal;
}
return result;
}
static OFCondition parseMetaHeader(DcmMetaInfo *metainfo,
xmlNodePtr current,
const OFBool parse)
{
/* check for valid node and correct name */
OFCondition result = checkNode(current, "meta-header");
if (result.good() && parse)
{
/* get child nodes */
current = current->xmlChildrenNode;
while (current != NULL)
{
/* ignore non-element nodes */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "element")) == 0)
parseElement(metainfo, current);
else if (!xmlIsBlankNode(current))
OFLOG_WARN(xml2dcmLogger, "unexpected node '" << current->name << "', 'element' expected, skipping");
/* proceed with next node */
current = current->next;
}
}
return result;
}
static OFCondition parseDataSet(DcmItem *dataset,
xmlNodePtr current,
E_TransferSyntax xfer)
{
OFCondition result = EC_Normal;
/* ignore blank (empty or whitespace only) nodes */
while ((current != NULL) && xmlIsBlankNode(current))
current = current->next;
while (current != NULL)
{
/* ignore non-element/sequence nodes */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "element")) == 0)
parseElement(dataset, current);
else if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "sequence")) == 0)
{
DcmElement *newElem = NULL;
/* create new sequence element */
if (createNewElement(current, newElem).good())
{
/* insert new sequence element into the dataset */
result = dataset->insert(newElem, OFTrue /*replaceOld*/);
if (result.good())
{
/* special handling for compressed pixel data */
if (newElem->getTag() == DCM_PixelData)
{
/* create new pixel sequence */
DcmPixelSequence *sequence = new DcmPixelSequence(DcmTag(DCM_PixelData, EVR_OB));
if (sequence != NULL)
{
/* ... insert it into the dataset and proceed with the pixel items */
OFstatic_cast(DcmPixelData *, newElem)->putOriginalRepresentation(xfer, NULL, sequence);
parsePixelSequence(sequence, current->xmlChildrenNode);
}
} else {
/* proceed parsing the items of the sequence */
parseSequence(OFstatic_cast(DcmSequenceOfItems *, newElem), current->xmlChildrenNode, xfer);
}
} else {
/* delete element if insertion failed */
delete newElem;
}
}
} else if (!xmlIsBlankNode(current))
OFLOG_WARN(xml2dcmLogger, "unexpected node '" << current->name << "', skipping");
/* proceed with next node */
current = current->next;
}
return result;
}
static OFCondition validateXmlDocument(xmlDocPtr doc)
{
OFCondition result = EC_Normal;
OFLOG_INFO(xml2dcmLogger, "validating XML document ...");
xmlGenericError(xmlGenericErrorContext, "--- libxml validating ---\n");
/* temporary buffer needed for errorFunction - more detailed explanation there */
OFString tmpErrorString;
/* create context for document validation */
xmlValidCtxt cvp;
cvp.userData = &tmpErrorString;
cvp.error = errorFunction;
cvp.warning = errorFunction;
/* validate the document */
const int valid = xmlValidateDocument(&cvp, doc);
xmlGenericError(xmlGenericErrorContext, "-------------------------\n");
if (!valid)
{
OFLOG_ERROR(xml2dcmLogger, "document does not validate");
result = EC_IllegalCall;
}
return result;
}
static OFCondition readXmlFile(const char *ifname,
DcmFileFormat &fileformat,
E_TransferSyntax &xfer,
const OFBool metaInfo,
const OFBool checkNamespace,
const OFBool validateDocument)
{
OFCondition result = EC_Normal;
xfer = EXS_Unknown;
xmlGenericError(xmlGenericErrorContext, "--- libxml parsing ------\n");
/* build an XML tree from the file */
xmlDocPtr doc = xmlParseFile(ifname);
xmlGenericError(xmlGenericErrorContext, "-------------------------\n");
if (doc != NULL)
{
/* validate document */
if (validateDocument)
result = validateXmlDocument(doc);
if (result.good())
{
/* check whether the document is of the right kind */
xmlNodePtr current = xmlDocGetRootElement(doc);
if (current != NULL)
{
/* check namespace declaration (if required) */
if (!checkNamespace || (xmlSearchNsByHref(doc, current, OFreinterpret_cast(const xmlChar *, DCMTK_XML_NAMESPACE_URI)) != NULL))
{
/* check whether to parse a "file-format" or "data-set" */
if (xmlStrcmp(current->name, OFreinterpret_cast(const xmlChar *, "file-format")) == 0)
{
OFLOG_INFO(xml2dcmLogger, "parsing file-format ...");
if (metaInfo)
OFLOG_INFO(xml2dcmLogger, "parsing meta-header ...");
else
OFLOG_INFO(xml2dcmLogger, "skipping meta-header ...");
current = current->xmlChildrenNode;
/* ignore blank (empty or whitespace only) nodes */
while ((current != NULL) && xmlIsBlankNode(current))
current = current->next;
/* parse/skip "meta-header" */
result = parseMetaHeader(fileformat.getMetaInfo(), current, metaInfo /*parse*/);
if (result.good())
{
current = current->next;
/* ignore blank (empty or whitespace only) nodes */
while ((current != NULL) && xmlIsBlankNode(current))
current = current->next;
}
}
/* there should always be a "data-set" node */
if (result.good())
{
OFLOG_INFO(xml2dcmLogger, "parsing data-set ...");
/* parse "data-set" */
result = checkNode(current, "data-set");
if (result.good())
{
DcmDataset *dataset = fileformat.getDataset();
/* determine stored transfer syntax */
xmlChar *xferUID = xmlGetProp(current, OFreinterpret_cast(const xmlChar *, "xfer"));
if (xferUID != NULL)
xfer = DcmXfer(OFreinterpret_cast(char *, xferUID)).getXfer();
result = parseDataSet(dataset, current->xmlChildrenNode, xfer);
/* free allocated memory */
xmlFree(xferUID);
}
}
if (result.bad() && xmlLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
{
/* dump XML document for debugging purposes */
xmlChar *str;
int size;
xmlDocDumpFormatMemory(doc, &str, &size, 1);
OFLOG_DEBUG(xmlLogger, str);
xmlFree(str);
}
} else {
OFLOG_ERROR(xml2dcmLogger, "document has wrong type, dcmtk namespace not found");
result = EC_IllegalCall;
}
} else {
OFLOG_ERROR(xml2dcmLogger, "document is empty: " << ifname);
result = EC_IllegalCall;
}
}
} else {
OFLOG_ERROR(xml2dcmLogger, "could not parse document: " << ifname);
result = EC_IllegalCall;
}
/* free allocated memory */
xmlFreeDoc(doc);
return result;
}
#define SHORTCOL 3
#define LONGCOL 21
int main(int argc, char *argv[])
{
OFBool opt_metaInfo = OFTrue;
OFBool opt_namespace = OFFalse;
OFBool opt_validate = OFFalse;
OFBool opt_generateUIDs = OFFalse;
OFBool opt_overwriteUIDs = OFFalse;
E_TransferSyntax opt_xfer = EXS_Unknown;
E_EncodingType opt_enctype = EET_ExplicitLength;
E_GrpLenEncoding opt_glenc = EGL_recalcGL;
E_PaddingEncoding opt_padenc = EPD_withoutPadding;
E_FileWriteMode opt_writeMode = EWM_fileformat;
OFCmdUnsignedInt opt_filepad = 0;
OFCmdUnsignedInt opt_itempad = 0;
/* set-up command line parameters and options */
OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, OFFIS_CONSOLE_DESCRIPTION, rcsid);
OFCommandLine cmd;
cmd.setOptionColumns(LONGCOL, SHORTCOL);
cmd.setParamColumn(LONGCOL + SHORTCOL + 4);
cmd.addParam("xmlfile-in", "XML input filename to be converted (stdin: \"-\")", OFCmdParam::PM_Mandatory);
cmd.addParam("dcmfile-out", "DICOM output filename", OFCmdParam::PM_Mandatory);
cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive);
cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive);
OFLog::addOptions(cmd);
cmd.addGroup("input options:");
cmd.addSubGroup("input file format:");
cmd.addOption("--read-meta-info", "+f", "read meta information if present (default)");
cmd.addOption("--ignore-meta-info", "-f", "ignore file meta information");
cmd.addGroup("processing options:");
cmd.addSubGroup("validation:");
cmd.addOption("--validate-document", "+Vd", "validate XML document against DTD");
cmd.addOption("--check-namespace", "+Vn", "check XML namespace in document root");
cmd.addSubGroup("unique identifiers:");
cmd.addOption("--generate-new-uids", "+Ug", "generate new Study/Series/SOP Instance UID");
cmd.addOption("--dont-overwrite-uids", "-Uo", "do not overwrite existing UIDs (default)");
cmd.addOption("--overwrite-uids", "+Uo", "overwrite existing UIDs");
cmd.addGroup("output options:");
cmd.addSubGroup("output file format:");
cmd.addOption("--write-file", "+F", "write file format (default)");
cmd.addOption("--write-dataset", "-F", "write data set without file meta information");
cmd.addOption("--update-meta-info", "+Fu", "update particular file meta information");
cmd.addSubGroup("output transfer syntax:");
cmd.addOption("--write-xfer-same", "+t=", "write with same TS as input (default)");
cmd.addOption("--write-xfer-little", "+te", "write with explicit VR little endian TS");
cmd.addOption("--write-xfer-big", "+tb", "write with explicit VR big endian TS");
cmd.addOption("--write-xfer-implicit", "+ti", "write with implicit VR little endian TS");
#ifdef WITH_ZLIB
cmd.addOption("--write-xfer-deflated", "+td", "write with deflated expl. VR little endian TS");
#endif
cmd.addSubGroup("post-1993 value representations:");
cmd.addOption("--enable-new-vr", "+u", "enable support for new VRs (UN/UT) (default)");
cmd.addOption("--disable-new-vr", "-u", "disable support for new VRs, convert to OB");
cmd.addSubGroup("group length encoding:");
cmd.addOption("--group-length-recalc", "+g=", "recalculate group lengths if present (default)");
cmd.addOption("--group-length-create", "+g", "always write with group length elements");
cmd.addOption("--group-length-remove", "-g", "always write without group length elements");
cmd.addSubGroup("length encoding in sequences and items:");
cmd.addOption("--length-explicit", "+e", "write with explicit lengths (default)");
cmd.addOption("--length-undefined", "-e", "write with undefined lengths");
cmd.addSubGroup("data set trailing padding (not with --write-dataset):");
cmd.addOption("--padding-retain", "-p=", "do not change padding\n(default if not --write-dataset)");
cmd.addOption("--padding-off", "-p", "no padding (implicit if --write-dataset)");
cmd.addOption("--padding-create", "+p", 2, "[f]ile-pad [i]tem-pad: integer",
"align file on multiple of f bytes\nand items on multiple of i bytes");
#ifdef WITH_ZLIB
cmd.addSubGroup("deflate compression level (only with --write-xfer-deflated):");
cmd.addOption("--compression-level", "+cl", 1, "[l]evel: integer (default: 6)",
"0=uncompressed, 1=fastest, 9=best compression");
#endif
/* evaluate command line */
prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
if (app.parseCommandLine(cmd, argc, argv, OFCommandLine::PF_ExpandWildcards))
{
/* check exclusive options first */
if (cmd.hasExclusiveOption())
{
if (cmd.findOption("--version"))
{
app.printHeader(OFTrue /*print host identifier*/);
COUT << OFendl << "External libraries used:" << OFendl;
#ifdef WITH_ZLIB
COUT << "- ZLIB, Version " << zlibVersion() << OFendl;
#endif
COUT << "- LIBXML, Version " << LIBXML_DOTTED_VERSION << OFendl;
return 0;
}
}
/* general options */
OFLog::configureFromCommandLine(cmd, app);
/* input options */
cmd.beginOptionBlock();
if (cmd.findOption("--read-meta-info"))
opt_metaInfo = OFTrue;
if (cmd.findOption("--ignore-meta-info"))
opt_metaInfo = OFFalse;
cmd.endOptionBlock();
/* processing options */
if (cmd.findOption("--validate-document"))
opt_validate = OFTrue;
if (cmd.findOption("--check-namespace"))
opt_namespace = OFTrue;
if (cmd.findOption("--generate-new-uids"))
opt_generateUIDs = OFTrue;
cmd.beginOptionBlock();
if (cmd.findOption("--dont-overwrite-uids"))
opt_overwriteUIDs = OFFalse;
if (cmd.findOption("--overwrite-uids"))
opt_overwriteUIDs = OFTrue;
cmd.endOptionBlock();
/* output options */
cmd.beginOptionBlock();
if (cmd.findOption("--write-file"))
opt_writeMode = EWM_fileformat;
if (cmd.findOption("--write-dataset"))
opt_writeMode = EWM_dataset;
cmd.endOptionBlock();
if (cmd.findOption("--update-meta-info"))
{
app.checkConflict("--update-meta-info", "--write-dataset", opt_writeMode == EWM_dataset);
opt_writeMode = EWM_updateMeta;
}
cmd.beginOptionBlock();
if (cmd.findOption("--write-xfer-same"))
opt_xfer = EXS_Unknown;
if (cmd.findOption("--write-xfer-little"))
opt_xfer = EXS_LittleEndianExplicit;
if (cmd.findOption("--write-xfer-big"))
opt_xfer = EXS_BigEndianExplicit;
if (cmd.findOption("--write-xfer-implicit"))
opt_xfer = EXS_LittleEndianImplicit;
#ifdef WITH_ZLIB
if (cmd.findOption("--write-xfer-deflated"))
opt_xfer = EXS_DeflatedLittleEndianExplicit;
#endif
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--enable-new-vr"))
{
dcmEnableUnknownVRGeneration.set(OFTrue);
dcmEnableUnlimitedTextVRGeneration.set(OFTrue);
}
if (cmd.findOption("--disable-new-vr"))
{
dcmEnableUnknownVRGeneration.set(OFFalse);
dcmEnableUnlimitedTextVRGeneration.set(OFFalse);
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--group-length-recalc"))
opt_glenc = EGL_recalcGL;
if (cmd.findOption("--group-length-create"))
opt_glenc = EGL_withGL;
if (cmd.findOption("--group-length-remove"))
opt_glenc = EGL_withoutGL;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--length-explicit"))
opt_enctype = EET_ExplicitLength;
if (cmd.findOption("--length-undefined"))
opt_enctype = EET_UndefinedLength;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--padding-retain"))
{
app.checkConflict("--padding-retain", "--write-dataset", opt_writeMode == EWM_dataset);
opt_padenc = EPD_noChange;
}
if (cmd.findOption("--padding-off"))
opt_padenc = EPD_withoutPadding;
if (cmd.findOption("--padding-create"))
{
app.checkConflict("--padding-create", "--write-dataset", opt_writeMode == EWM_dataset);
app.checkValue(cmd.getValueAndCheckMin(opt_filepad, 0));
app.checkValue(cmd.getValueAndCheckMin(opt_itempad, 0));
opt_padenc = EPD_withPadding;
}
cmd.endOptionBlock();
#ifdef WITH_ZLIB
if (cmd.findOption("--compression-level"))
{
OFCmdUnsignedInt comprLevel = 0;
app.checkDependence("--compression-level", "--write-xfer-deflated", opt_xfer == EXS_DeflatedLittleEndianExplicit);
app.checkValue(cmd.getValueAndCheckMinMax(comprLevel, 0, 9));
dcmZlibCompressionLevel.set(OFstatic_cast(int, comprLevel));
}
#endif
}
/* print resource identifier */
OFLOG_DEBUG(xml2dcmLogger, rcsid << OFendl);
/* make sure data dictionary is loaded */
if (!dcmDataDict.isDictionaryLoaded())
{
OFLOG_WARN(xml2dcmLogger, "no data dictionary loaded, check environment variable: "
<< DCM_DICT_ENVIRONMENT_VARIABLE);
}
/* check for compatible libxml version */
LIBXML_TEST_VERSION
/* temporary buffer needed for errorFunction - more detailed explanation there */
OFString tmpErrorString;
/* initialize the XML library (only required for MT-safety) */
xmlInitParser();
/* substitute default entities (XML mnenonics) */
xmlSubstituteEntitiesDefault(1);
/* add line number to debug messages */
xmlLineNumbersDefault(1);
xmlGetWarningsDefaultValue = 1;
xmlSetGenericErrorFunc(&tmpErrorString, errorFunction);
OFCondition result = EC_Normal;
const char *opt_ifname = NULL;
const char *opt_ofname = NULL;
cmd.getParam(1, opt_ifname);
cmd.getParam(2, opt_ofname);
/* check filenames */
if ((opt_ifname == NULL) || (strlen(opt_ifname) == 0))
{
OFLOG_ERROR(xml2dcmLogger, OFFIS_CONSOLE_APPLICATION << ": invalid input filename: <empty string>");
result = EC_IllegalParameter;
}
if ((opt_ofname == NULL) || (strlen(opt_ofname) == 0))
{
OFLOG_ERROR(xml2dcmLogger, OFFIS_CONSOLE_APPLICATION << ": invalid output filename: <empty string>");
result = EC_IllegalParameter;
}
if (result.good())
{
DcmFileFormat fileformat;
E_TransferSyntax xfer;
OFLOG_INFO(xml2dcmLogger, "reading XML input file: " << opt_ifname);
/* read XML file and feed data into DICOM fileformat */
result = readXmlFile(opt_ifname, fileformat, xfer, opt_metaInfo, opt_namespace, opt_validate);
if (result.good())
{
DcmDataset *dataset = fileformat.getDataset();
/* generate new UIDs (if required) */
if (opt_generateUIDs)
{
char uid[100];
if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_StudyInstanceUID))
{
OFLOG_INFO(xml2dcmLogger, "generating new Study Instance UID");
dataset->putAndInsertString(DCM_StudyInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_STUDY_UID_ROOT));
}
if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_SeriesInstanceUID))
{
OFLOG_INFO(xml2dcmLogger, "generating new Series Instance UID");
dataset->putAndInsertString(DCM_SeriesInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_SERIES_UID_ROOT));
}
if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_SOPInstanceUID))
{
OFLOG_INFO(xml2dcmLogger, "generating new SOP Instance UID");
dataset->putAndInsertString(DCM_SOPInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_INSTANCE_UID_ROOT));
}
}
OFLOG_INFO(xml2dcmLogger, "writing DICOM output file: " << opt_ofname);
/* determine transfer syntax to write the file */
if ((opt_xfer == EXS_Unknown) && (xfer != EXS_Unknown))
opt_xfer = xfer;
/* check whether this is possible */
if (fileformat.canWriteXfer(opt_xfer))
{
/* check whether pixel data is compressed */
if ((opt_writeMode == EWM_dataset) && DcmXfer(xfer).isEncapsulated())
{
OFLOG_ERROR(xml2dcmLogger, "encapsulated pixel data require file format, ignoring --write-dataset");
opt_writeMode = EWM_fileformat;
}
/* write DICOM file */
result = fileformat.saveFile(opt_ofname, opt_xfer, opt_enctype, opt_glenc, opt_padenc,
OFstatic_cast(Uint32, opt_filepad), OFstatic_cast(Uint32, opt_itempad), opt_writeMode);
if (result.bad())
OFLOG_ERROR(xml2dcmLogger, result.text() << ": writing file: " << opt_ofname);
} else {
OFLOG_ERROR(xml2dcmLogger, "no conversion to transfer syntax " << DcmXfer(opt_xfer).getXferName() << " possible!");
result = EC_CannotChangeRepresentation;
}
}
}
/* clean up XML library before quitting */
xmlCleanupParser();
return result.status();
}
#else /* WITH_LIBXML */
int main(int, char *[])
{
CERR << rcsid << OFendl << OFFIS_CONSOLE_DESCRIPTION << OFendl << OFendl
<< OFFIS_CONSOLE_APPLICATION " requires the libxml library." << OFendl
<< "This " OFFIS_CONSOLE_APPLICATION " has been configured and compiled without libxml." << OFendl
<< "Please reconfigure your system and recompile if appropriate." << OFendl;
return 0;
}
#endif /* WITH_LIBXML */
/*
* CVS/RCS Log:
* $Log: xml2dcm.cc,v $
* Revision 1.34 2010-12-15 13:59:57 uli
* Fixed a problem with a missing prototype for vsnprintf on HP-UX.
*
* Revision 1.33 2010-10-21 08:35:41 joergr
* Removed redundant definition of logger variable for libxml.
*
* Revision 1.32 2010-10-14 13:13:30 joergr
* Updated copyright header. Added reference to COPYRIGHT file.
*
* Revision 1.31 2010-06-03 10:30:17 joergr
* Replaced calls to strerror() by new helper function OFStandard::strerror()
* which results in using the thread safe version of strerror() if available.
*
* Revision 1.30 2010-05-20 09:22:31 joergr
* Use new OFStandard::getFileSize() method where appropriate.
*
* Revision 1.29 2009-11-13 13:20:23 joergr
* Fixed minor issues in log output.
*
* Revision 1.28 2009-11-04 09:58:06 uli
* Switched to logging mechanism provided by the "new" oflog module
*
* Revision 1.27 2009-08-21 09:25:13 joergr
* Added parameter 'writeMode' to save/write methods which allows for specifying
* whether to write a dataset or fileformat as well as whether to update the
* file meta information or to create a new file meta information header.
*
* Revision 1.26 2009-05-07 09:05:09 joergr
* Added new command line options that allow for generating new Study/Series/SOP
* Instance UIDs (incl. an option for overwriting existing values).
*
* Revision 1.25 2009-04-30 14:56:39 joergr
* Fixed memory leak in putElementContent() for base64 encoded data.
*
* Revision 1.24 2008-11-03 15:50:42 joergr
* Added ZLIB related output options --write-xfer-deflated, --compression-level.
*
* Revision 1.23 2008-09-25 14:38:48 joergr
* Moved output of resource identifier in order to avoid printing the same
* information twice.
*
* Revision 1.22 2008-09-25 11:19:48 joergr
* Added support for printing the expanded command line arguments.
* Always output the resource identifier of the command line tool in debug mode.
*
* Revision 1.21 2008-09-24 13:00:48 joergr
* Added new command line option --update-meta-info that allows for updating
* particular information in the file meta-header (e.g. SOP instance UID).
*
* Revision 1.20 2007/07/04 12:51:05 joergr
* Added support for binary data (e.g. pixel data) stored in a separate file.
*
* Revision 1.19 2006/08/15 15:50:56 meichel
* Updated all code in module dcmdata to correctly compile when
* all standard C++ classes remain in namespace std.
*
* Revision 1.18 2006/07/27 13:52:42 joergr
* Changed parameter "exclusive" of method addOption() from type OFBool into an
* integer parameter "flags". Prepended prefix "PF_" to parseLine() flags.
* Option "--help" is no longer an exclusive option by default.
*
* Revision 1.17 2006/07/11 13:59:20 joergr
* Fixed wrong warning message about multiple Specific Character Set attributes
* in DICOMDIR files.
*
* Revision 1.16 2005/12/16 15:46:41 meichel
* Declared libxml2 callback functions as extern "C"
*
* Revision 1.15 2005/12/09 12:38:51 meichel
* Added missing include for dcdebug.h
*
* Revision 1.14 2005/12/08 15:40:54 meichel
* Changed include path schema for all DCMTK header files
*
* Revision 1.13 2005/11/30 12:51:45 joergr
* Added missing header file "dcdebug.h".
*
* Revision 1.12 2005/03/22 13:55:50 joergr
* Added call of macro LIBXML_TEST_VERSION.
*
* Revision 1.11 2004/11/29 17:04:08 joergr
* Added support for UTF-8 character set.
*
* Revision 1.10 2004/08/03 10:06:18 joergr
* Added new option that allows to ignore the file meta information.
*
* Revision 1.9 2004/03/25 17:27:36 joergr
* Solved issue with function pointer to std::fprintf or fprintf, respectively.
*
* Revision 1.8 2004/03/22 16:55:11 joergr
* Replaced tabs by spaces.
*
* Revision 1.7 2004/02/20 18:06:43 joergr
* Avoid wrong warning for LUTData (0028,3006) having a VR of US or SS.
*
* Revision 1.6 2004/01/16 10:53:53 joergr
* Adapted type casts to new-style typecast operators defined in ofcast.h.
*
* Revision 1.5 2003/08/08 14:46:24 joergr
* Made libxml output consistent with new xml2dsr command line tool.
*
* Revision 1.4 2003/06/17 17:36:04 joergr
* Distinguish more strictly between OFBool and int (required when HAVE_CXX_BOOL
* is defined).
*
* Revision 1.3 2003/05/20 08:52:56 joergr
* Minor code corrections.
*
* Revision 1.2 2003/04/22 08:25:48 joergr
* Adapted code to also compile trouble-free without libxml support (report a
* message that libxml library is required).
*
* Revision 1.1 2003/04/17 18:57:08 joergr
* Added new command line tool that allows to convert an XML document to DICOM
* file or dataset.
*
*
*/
|