File: element.cpp

package info (click to toggle)
mrtrix 0.2.12-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 5,980 kB
  • ctags: 4,172
  • sloc: cpp: 26,485; python: 913; xml: 39; makefile: 22; sh: 10
file content (423 lines) | stat: -rw-r--r-- 14,144 bytes parent folder | download
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
/*
    Copyright 2008 Brain Research Institute, Melbourne, Australia

    Written by J-Donald Tournier, 27/06/08.

    This file is part of MRtrix.

    MRtrix 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.

    MRtrix 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 MRtrix.  If not, see <http://www.gnu.org/licenses/>.


    02-10-2008 J-Donald Tournier <d.tournier@brain.org.au>
    * extra sanity check to make sure that each element fits within the file.

    31-10-2008 J-Donald Tournier <d.tournier@brain.org.au>
    * only attempt to read a "truncated format" DICOM file if the extension is ".dcm"

    18-12-2008 J-Donald Tournier <d.tournier@brain.org.au>
    * printout of DICOM group & element is now in hexadecimal

    17-03-2009 J-Donald Tournier <d.tournier@brain.org.au>
    * modify to allow use of either TR1 unordered map or SGI hash_map for the DICOM dictionary
    
    09-09-2009 J-Donald Tournier <d.tournier@brain.org.au>
    * include <cstdio> to allow compilation on Fedora 11

    03-03-2010 J-Donald Tournier <d.tournier@brain.org.au>
    * fix bug in handling of IS sequences

    16-08-2010 J-Donald Tournier <d.tournier@brain.org.au>
    * fix bug in handling of big-endian files

*/

#include <cstdio>
#include <glibmm/stringutils.h>

#include "file/dicom/element.h"
#include "get_set.h"

namespace MR {
  namespace File {
    namespace Dicom {

      void Element::set (const String& filename)
      {
        group = element = VR = 0;
        size = 0;
        start = data = next = NULL;
        is_BE = previous_BO_was_BE = false;
        sequence.clear();

        fmap.init (filename);

        if (fmap.size() < 256) 
          throw Exception ("\"" + fmap.name() + "\" is too small to be a valid DICOM file", 3);
        fmap.map();

        next = (guint8*) fmap.address();

        if (memcmp (next + 128, "DICM", 4)) {
          is_explicit = false;
          debug ("DICOM magic number not found in file \"" + fmap.name() + "\" - trying truncated format");
          if (!Glib::str_has_suffix (fmap.name(), ".dcm")) 
            throw Exception ("file \"" + fmap.name() + "\" does not have the DICOM magic number or the .dcm extension - assuming not DICOM");
        }
        else next += 132;

        try { set_explicit_encoding(); }
        catch (Exception) {
          fmap.unmap();
          throw Exception ("\"" + fmap.name() + "\" is not a valid DICOM file", 3);
        }
      }






      void Element::set_explicit_encoding ()
      {
        if (read_GR_EL()) throw Exception ("\"" + fmap.name() + "\" is too small to be DICOM", 3);

        is_explicit = true;
        next = start;
        VR = ByteOrder::BE (*((guint16*) (start+4)));

        if ((VR == VR_OB) | (VR == VR_OW) | (VR == VR_OF) | (VR == VR_SQ) |
            (VR == VR_UN) | (VR == VR_AE) | (VR == VR_AS) | (VR == VR_AT) |
            (VR == VR_CS) | (VR == VR_DA) | (VR == VR_DS) | (VR == VR_DT) |
            (VR == VR_FD) | (VR == VR_FL) | (VR == VR_IS) | (VR == VR_LO) |
            (VR == VR_LT) | (VR == VR_PN) | (VR == VR_SH) | (VR == VR_SL) |
            (VR == VR_SS) | (VR == VR_ST) | (VR == VR_TM) | (VR == VR_UI) |
            (VR == VR_UL) | (VR == VR_US) | (VR == VR_UT)) return;

        debug ("using implicit DICOM encoding");
        is_explicit = false;
      }






      bool Element::read_GR_EL ()
      {
        group = element = VR = 0;
        size = 0;
        start = next;
        data = next = NULL;

        if (start < (guint8*) fmap.address()) throw Exception ("invalid DICOM element", 3);
        if (start + 8 > (guint8*) fmap.address() + fmap.size()) return (true);

        is_BE = previous_BO_was_BE;

        group = get<guint16> (start, is_BE);

        if (group == GROUP_BYTE_ORDER_SWAPPED) {
          if (!is_BE) 
            throw Exception ("invalid DICOM group ID " + str (group) + " in file \"" + fmap.name() + "\"", 3);

          is_BE = false;
          group = GROUP_BYTE_ORDER;
        }
        element = get<guint16> (start+2, is_BE);

        return (false);
      }






      bool Element::read ()
      {
        if (read_GR_EL()) return (false);

        data = start + 8;
        if ((is_explicit && group != GROUP_SEQUENCE) || group == GROUP_BYTE_ORDER) {
          // explicit encoding:
          VR = ByteOrder::BE (*((guint16*) (start+4)));
          if (VR == VR_OB || VR == VR_OW || VR == VR_OF || VR == VR_SQ || VR == VR_UN || VR == VR_UT) {
            size = get<guint32> (start+8, is_BE);
            data += 4;
          }
          else size = get<guint16> (start+6, is_BE);
        }
        else {
          // implicit encoding:
          String name = tag_name();
          if (!name.size()) {
            if (group%2 == 0) 
              debug ("WARNING: unknown DICOM tag (" + str (group) + ", " + str (element) 
                  + ") with implicit encoding in file \"" + fmap.name() + "\"");
            VR = VR_UN;
          }
          else {
            gchar t[] = { name[0], name[1] };
            VR = ByteOrder::BE (*((guint16*) t));
          }
          size = get<guint32> (start+4, is_BE);
        }


        next = data;
        if (size == LENGTH_UNDEFINED) {
          if (VR != VR_SQ && !(group == GROUP_SEQUENCE && element == ELEMENT_SEQUENCE_ITEM)) 
            throw Exception ("undefined length used for DICOM tag " + ( tag_name().size() ? tag_name().substr (2) : "" ) 
                + " (" + str (group) + ", " + str (element) 
                + ") in file \"" + fmap.name() + "\"", 3);
        }
        else if (next+size > (guint8*) fmap.address() + fmap.size()) 
          throw Exception ("file \"" + fmap.name() + "\" is too small to contain DICOM elements specified", 3);
        else if (size%2) 
          throw Exception ("odd length (" + str (size) + ") used for DICOM tag " + ( tag_name().size() ? tag_name().substr (2) : "" ) 
              + " (" + str (group) + ", " + str (element) + ") in file \"" + fmap.name() + "", 3);
        else if (VR != VR_SQ && ( group != GROUP_SEQUENCE || element != ELEMENT_SEQUENCE_ITEM ) ) 
          next += size;



        if (sequence.size()) 
          if ((sequence.back().end && data > sequence.back().end) || 
              (group == GROUP_SEQUENCE && element == ELEMENT_SEQUENCE_DELIMITATION_ITEM)) 
            sequence.pop_back();

        if (VR == VR_SQ) {
          if (size == LENGTH_UNDEFINED) 
            sequence.push_back (Sequence (group, element, NULL)); 
          else 
            sequence.push_back (Sequence (group, element, data + size));
        }




        switch (group) {
          case GROUP_BYTE_ORDER:
            switch (element) {
              case ELEMENT_TRANSFER_SYNTAX_UID:
                if (strncmp ((const gchar*) data, "1.2.840.10008.1.2.1", size) == 0) {
                  is_BE = previous_BO_was_BE = false; // explicit VR Little Endian
                  is_explicit = true;
                }
                else if (strncmp ((const gchar*) data, "1.2.840.10008.1.2.2", size) == 0) {
                  is_BE = previous_BO_was_BE = true; // Explicit VR Big Endian
                  is_explicit = true;
                }
                else if (strncmp ((const gchar*) data, "1.2.840.10008.1.2", size) == 0) {
                  is_BE = previous_BO_was_BE = false; // Implicit VR Little Endian
                  is_explicit = false;
                }
                else if (strncmp ((const gchar*) data, "1.2.840.10008.1.2.1.99", size) == 0) {
                  throw Exception ("DICOM deflated explicit VR little endian transfer syntax not supported");
                }
                else error ("unknown DICOM transfer syntax: \"" + String ((const gchar*) data, size) 
                    + "\" in file \"" + fmap.name() + "\" - ignored");
                break;
            }

            break;
        }

        return (true);
      }












      ElementType Element::type () const
      {
        if (!VR) return (INVALID);
        if (VR == VR_FD || VR == VR_FL) return (FLOAT);
        if (VR == VR_SL || VR == VR_SS) return (INT);
        if (VR == VR_UL || VR == VR_US) return (UINT);
        if (VR == VR_SQ) return (SEQ);
        if (VR == VR_AE || VR == VR_AS || VR == VR_CS || VR == VR_DA ||
            VR == VR_DS || VR == VR_DT || VR == VR_IS || VR == VR_LO ||
            VR == VR_LT || VR == VR_PN || VR == VR_SH || VR == VR_ST ||
            VR == VR_TM || VR == VR_UI || VR == VR_UT || VR == VR_AT) return (STRING);
        return (OTHER);
      }



      std::vector<gint32> Element::get_int () const
      {
        std::vector<gint32> V;
        if (VR == VR_SL) 
          for (const guint8* p = data; p < data + size; p += sizeof (gint32))
            V.push_back (get<gint32> (p, is_BE));
        else if (VR == VR_SS)
          for (const guint8* p = data; p < data + size; p += sizeof (gint16)) 
            V.push_back (get<gint16> (p, is_BE));
        else if (VR == VR_IS) {
          std::vector<String> strings (split (String ((const gchar*) data, size), "\\", false));
          V.resize (strings.size());
          for (guint n = 0; n < V.size(); n++) V[n] = to<gint32> (strings[n]);
        }
        return (V);
      }




      std::vector<guint32> Element::get_uint () const
      {
        std::vector<guint32> V;
        if (VR == VR_UL) 
          for (const guint8* p = data; p < data + size; p += sizeof (guint32))
            V.push_back (get<guint32> (p, is_BE));
        else if (VR == VR_US)
          for (const guint8* p = data; p < data + size; p += sizeof (guint16)) 
            V.push_back (get<guint16> (p, is_BE));
        else if (VR == VR_IS) {
          std::vector<String> strings (split (String ((const gchar*) data, size), "\\", false));
          V.resize (strings.size());
          for (guint n = 0; n < V.size(); n++) V[n] = to<guint32> (strings[n]);
        }
        return (V);
      }



      std::vector<double> Element::get_float () const
      {
        std::vector<double> V;
        if (VR == VR_FD) 
          for (const guint8* p = data; p < data + size; p += sizeof (float64))
            V.push_back (get<float64> (p, is_BE));
        else if (VR == VR_FL)
          for (const guint8* p = data; p < data + size; p += sizeof (float32)) 
            V.push_back (get<float32> (p, is_BE));
        else if (VR == VR_DS) {
          std::vector<String> strings (split (String ((const gchar*) data, size), "\\", false));
          V.resize (strings.size());
          for (guint n = 0; n < V.size(); n++) V[n] = to<double> (strings[n]);
        }
        return (V);
      }



      

      std::vector<String> Element::get_string () const
      { 
        if (VR == VR_AT) {
          std::vector<String> strings;
          strings.push_back (printf ("%02X %02X", get<guint16> (data, is_BE), get<guint16> (data+2, is_BE)));
          return strings;
        }

        std::vector<String> strings (split (String ((const gchar*) data, size), "\\", false)); 
        for (std::vector<String>::iterator i = strings.begin(); i != strings.end(); ++i) {
          *i = strip (*i);
          replace (*i, '^', ' ');
        }
        return (strings);
      }



      namespace {
        template <class T> inline void print_vec (const std::vector<T>& V)
        { for (guint n = 0; n < V.size(); n++) fprintf (stdout, "%s ", str (V[n]).c_str()); }
      }






      void Element::print() const
      {
        String name = tag_name();
        fprintf (stdout, "  [DCM] %*s : ", int(2*level()), ( name.size() ? name.substr(2).c_str() : "unknown" ));
        switch (type()) {
          case INT: print_vec (get_int()); break;
          case UINT: print_vec (get_int()); break;
          case FLOAT: print_vec (get_int()); break;
          case STRING: 
            if (group == GROUP_DATA && element == ELEMENT_DATA) fprintf (stdout, "(data)");
            else print_vec (get_int());
            break;
          case SEQ: fprintf (stdout, "(sequence)"); break;
          default: fprintf (stdout, "unknown data type");
        }
        if (group%2) fprintf (stdout, " [ PRIVATE ]\n");
        else fprintf (stdout, "\n");
      }







      std::ostream& operator<< (std::ostream& stream, const Element& item)
      {
        const String& name (item.tag_name());

        stream << "[DCM] ";
        guint indent = item.level() + ( item.VR == VR_SQ ? 0 : 1 );
        for (guint i = 0; i < indent; i++) 
          stream << "  ";
        if (item.VR == VR_SQ) 
          stream << "+ ";
        else if (item.group == GROUP_SEQUENCE && item.element == ELEMENT_SEQUENCE_ITEM) 
          stream << "- ";
        else 
          stream << "  ";
        stream << printf ("%02X %02X ", item.group, item.element)  
            + ((const gchar*) &item.VR)[1] + ((const gchar*) &item.VR)[0] + " " 
            + str ( item.size == LENGTH_UNDEFINED ? 0 : item.size ) + " " 
            + str (item.offset (item.start)) + " " + ( name.size() ? name.substr (2) : "unknown" ) + " ";


        switch (item.type()) {
          case INT: stream << item.get_int(); break;
          case UINT: stream << item.get_uint(); break;
          case FLOAT: stream << item.get_float(); break;
          case STRING:
            if (item.group == GROUP_DATA && item.element == ELEMENT_DATA) stream << "(data)";
            else stream << item.get_string(); 
            break;
          case SEQ:
            break;
          default:
            if (item.group != GROUP_SEQUENCE || item.element != ELEMENT_SEQUENCE_ITEM)
              stream << "unknown data type";
        }
        if (item.group%2) stream << " [ PRIVATE ]";

        return (stream);
      }


    }
  }
}