File: Checker.cpp

package info (click to toggle)
mediaconch 25.04-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,828 kB
  • sloc: ansic: 126,293; cpp: 39,636; javascript: 34,300; xml: 2,950; sh: 2,121; makefile: 200; python: 183
file content (872 lines) | stat: -rw-r--r-- 29,750 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
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
/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "Common/Version.h"
#include "Checker.h"

#include <functional>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <sstream>

//---------------------------------------------------------------------------
using namespace tfsxml;

//TODO: mmt
//TODO: reference_file

//---------------------------------------------------------------------------
// Helpers
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, tfsxml_string const& in)
{
    if (in.len)
        out << std::string(in.buf, in.len);

    return out;
}

//---------------------------------------------------------------------------
std::string xml_encode(const std::string& data)
{
    std::stringstream ss;
    for (size_t pos=0; pos<data.size(); pos++)
    {
        switch (data[pos])
        {
            case '\'': ss << "&apos;"; break;
            case '"': ss << "&quot;"; break;
            case '&': ss << "&amp;"; break;
            case '<': ss << "&lt;"; break;
            case '>': ss << "&gt;"; break;
            case '\t': ss << "&#x9;"; break;
            case '\n': ss << "&#xA;"; break;
            case '\r':
                ss << "&#xA;";
                if (pos+1<data.size() && data[pos+1]=='\n') // translate the #xD #xA sequence to a single #xA character
                    pos++;
            break;
            default: if ((unsigned char)data[pos]>=0x20) ss << data[pos]; // Ignore others control characters
        }
    }
    return ss.str();
}

//---------------------------------------------------------------------------
std::string indent(size_t level)
{
    return std::string( level*2, ' ');
}

//---------------------------------------------------------------------------
int tfsxml_next_named(tfsxml_string* tfsxml_priv, tfsxml_string* result, const char* name)
{
    while (!tfsxml_next(tfsxml_priv, result))
    {
        if (!tfsxml_strcmp_charp(*result, name))
            return 0;
    }

    return -1;
}

//---------------------------------------------------------------------------
int tfsxml_hasvalue(tfsxml_string* priv)
{
    const char* buf = priv->buf;
    unsigned len = priv->len;
    while (len)
    {
        len--;
        switch (*buf)
        {
            case '\n':
            case '\t':
            case '\r':
            case ' ':
                break;
            case '<':
                if (!len)
                    return 1;
                buf++;
                switch (*buf)
                {
                    case '!':
                    case '/':
                        return 0;
                    default:
                        return -1;
                }
            default:
                return 0;
        }
    }
    return 1;
}

//---------------------------------------------------------------------------
std::string tokenize(const std::string& scope, const std::string& list, const std::string& delimiter)
{
    std::stringstream ss;

    //TODO: mmt
    if (scope.empty() || scope=="mi")
    {
        std::istringstream iss(list);
        for (std::string token; std::getline(iss, token, '/');)
            ss << "/mi:" << token;
    }

    return ss.str();
}


//---------------------------------------------------------------------------
namespace MediaConch {

//---------------------------------------------------------------------------
// Policy
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
PolicyChecker::PolicyElement::PolicyElement() : resolved(false), pass_count(0), info_count(0), warn_count(0), fail_count(0)
{
}

//---------------------------------------------------------------------------
PolicyChecker::PolicyElement::~PolicyElement()
{
    while (children.size())
    {
        delete children.back();
        children.pop_back();
    }
}

//---------------------------------------------------------------------------
PolicyChecker::Element::Level PolicyChecker::PolicyElement::error_level()
{
    if (level=="info")
        return LEVEL_INFO;
    else if (level=="warn")
        return LEVEL_WARN;
    else if (level=="fail")
        return LEVEL_FAIL;

    return LEVEL_NONE;
}

//---------------------------------------------------------------------------
void PolicyChecker::PolicyElement::resolve()
{
    for (size_t pos=0; pos<children.size(); pos++)
    {
        switch (children[pos]->result())
        {
        case RESULT_PASS:
            pass_count++; break;
        case RESULT_INFO:
            info_count++; break;
        case RESULT_WARN:
            warn_count++; break;
        case RESULT_FAIL:
            fail_count++; break;
        default:
            break;
        }
    }

    resolved=true;
}

//---------------------------------------------------------------------------
PolicyChecker::Element::Result PolicyChecker::PolicyElement::result()
{
    if(!resolved)
        resolve();

    Result to_return=RESULT_PASS;

    if (type=="and")
    {
        if (fail_count)
            to_return=RESULT_FAIL;
        else if (warn_count)
            to_return=RESULT_WARN;
        else if (info_count)
            to_return=RESULT_INFO;
        else
            to_return=RESULT_PASS;
    }
    else if (type=="or")
    {
        if (fail_count && !warn_count && !info_count && !pass_count)
            to_return=RESULT_FAIL;
        else if (warn_count && !info_count && !pass_count)
            to_return=RESULT_WARN;
        else if (info_count && !pass_count)
            to_return=RESULT_INFO;
        else
            to_return=RESULT_PASS;
    }

    if (error_level()>LEVEL_NONE)
    {
        if (to_return>RESULT_INFO && error_level()==LEVEL_INFO)
            to_return=RESULT_INFO;
        else if (to_return>RESULT_WARN && error_level()==LEVEL_WARN)
            to_return=RESULT_WARN;
    }



    return to_return;
}

//---------------------------------------------------------------------------
std::string PolicyChecker::PolicyElement::to_string(size_t level, bool verbose)
{
    if(!resolved)
        resolve();

    std::string outcome_str;
    switch (result())
    {
    case RESULT_FAIL:
        outcome_str="fail"; break;
    case RESULT_WARN:
        outcome_str="warn"; break;
    case RESULT_INFO:
        outcome_str="info"; break;
    case RESULT_PASS:
        outcome_str="pass"; break;
    }

    std::stringstream ss;

    ss << indent(level) << "<policy name=\"" << xml_encode(name) << "\" type=\"" << xml_encode(type);
    if (!this->level.empty())
        ss << "\" level=\"" << xml_encode(this->level);
    ss << "\" rules_run=\"" << children.size() << "\" pass_count=\"" << pass_count << "\" info_count=\"" << info_count << "\" warn_count=\"" << warn_count
       << "\" fail_count=\"" << fail_count << "\" outcome=\"" << outcome_str << "\">" << std::endl;
    level++;
    if (!description.empty())
        ss << indent(level) << "<description>" << description << "</description>" << std::endl;
    for (size_t pos=0; pos<tags.size(); pos++)
        ss << indent(level) << "<tag>" << tags[pos] << "</tag>" << std::endl;
    for (size_t pos=0; pos<children.size(); pos++)
        ss << children[pos]->to_string(level, verbose);
    level--;
    ss << indent(level) << "</policy>" << std::endl;

    return ss.str();
}

//---------------------------------------------------------------------------
// Rule
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
PolicyChecker::RuleElement::RuleElement() : resolved(false), pass(false), tracks(0), source(NULL)
{
}

//---------------------------------------------------------------------------
PolicyChecker::RuleElement::~RuleElement()
{
    if (source)
        delete source;
}

//---------------------------------------------------------------------------
void PolicyChecker::RuleElement::reset()
{
    resolved=false;
    pass=false;
    tracks=0;
    values.clear();
    if (source)
        source->values.clear();
}

//---------------------------------------------------------------------------
bool  PolicyChecker::RuleElement::compare(const std::string& v1, const std::string& v2)
{
    bool to_return = false;

    char* val_end=NULL;
    double val = strtod(v2.c_str(), &val_end);
    char* ref_end=NULL;
    double ref = strtod(v1.c_str(), &ref_end);

    if (operand=="starts with")
    {
        to_return = v2.rfind(v1, 0) == 0;
    }
    else if (operand=="must not start with")
    {
        to_return = v2.rfind(v1, 0) != 0;
    }
    else if (operand == "<")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val < ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) < 0;
    }
    else if (operand == "<=")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val <= ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) <= 0;
    }
    else if (operand == "=")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val == ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) == 0;
    }
    else if (operand == "!=")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val != ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) != 0;
    }
    else if (operand == ">=")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val >= ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) >= 0;
    }
    else if (operand == ">")
    {
        if (!strlen(val_end) && !strlen(ref_end))
            to_return = val > ref;
        else
            to_return = strcmp(v2.c_str(), v1.c_str()) > 0;
    }

    if (!to_return)
        failing_values.push_back(v2);

    return to_return;
}

//---------------------------------------------------------------------------
PolicyChecker::Element::Level PolicyChecker::RuleElement::error_level()
{
    if (level=="info")
        return LEVEL_INFO;
    else if (level=="warn")
        return LEVEL_WARN;
    else if (level=="fail")
        return LEVEL_FAIL;

    return LEVEL_NONE;
}

//---------------------------------------------------------------------------
void PolicyChecker::RuleElement::resolve()
{
    if (operand=="" || operand=="exists")
    {
        if (occurrence=="all")
            pass=!values.empty() && values.size()==tracks;
        else
            pass=!values.empty();
    }
    else if (operand=="must not exist")
    {
        if (occurrence=="any")
            pass=values.size()<tracks;
        else // keep old behavior for legacy "*" value
            pass=values.empty();
    }
    else if (operand=="starts with" || operand=="must not start with" || operand=="<" || operand=="<=" || operand=="="  || operand=="!=" || operand==">=" || operand==">")
    {
        std::vector<bool> results;

        if (values.empty())
           pass=operand=="must not start with" ? true : false;
        else
        {
            for (std::pair<const char*, std::string> value : values)
            {
                if (source)
                {
                    std::vector<bool> r2;
                    for (std::pair<const char*, std::string> v2 : source->values)
                    {
                        if ((occurrence.empty() || occurrence=="any" || occurrence=="*" ||
                            source->occurrence.empty() || source->occurrence=="all" ||
                            source->occurrence=="any" || source->occurrence=="*") &&
                            v2.first==value.first)
                            continue;

                        r2.push_back(compare(v2.second, value.second));
                    }

                    if (r2.empty())
                        continue;

                    if (source->occurrence=="all")
                        results.push_back(std::all_of(r2.begin(), r2.end(), [this](bool result) { return result; }));
                    else
                        results.push_back(std::any_of(r2.begin(), r2.end(), [this](bool result) { return result; }));
                }
                else
                    results.push_back(compare(requested, value.second));
            }

            if (!results.empty())
            {
                if (occurrence=="all")
                    pass=std::all_of(results.begin(), results.end(), [this](bool result) { return result; });
                else
                    pass=std::any_of(results.begin(), results.end(), [this](bool result) { return result; });
            }
        }
    }

    resolved=true;
}

//---------------------------------------------------------------------------
PolicyChecker::Element::Result PolicyChecker::RuleElement::result()
{
    if(!resolved)
        resolve();

    if (!pass)
    {
        if (error_level()==LEVEL_INFO)
            return RESULT_INFO;
        else if (error_level()==LEVEL_WARN)
            return RESULT_WARN;
        else
            return RESULT_FAIL;
    }
    return RESULT_PASS;
}

//---------------------------------------------------------------------------
std::string PolicyChecker::RuleElement::to_string(size_t level, bool verbose)
{
    std::stringstream ss;

    std::string outcome_str;
    switch (result())
    {
    case RESULT_FAIL:
        outcome_str="fail"; break;
    case RESULT_WARN:
        outcome_str="warn"; break;
    case RESULT_INFO:
        outcome_str="info"; break;
    case RESULT_PASS:
        outcome_str="pass"; break;
    }

    std::string value_str;
    if (result()>RESULT_PASS)
        value_str=failing_values.size() ? failing_values.front() : std::string();
    else if (verbose)
        value_str=values.size() ? values.begin()->second : std::string();

    ss << indent(level) << "<rule name=\"" << xml_encode(name) << "\"";
    if (!scope.empty())
        ss << " scope=\"" << xml_encode(scope) << "\"";
    ss << " value=\"" << xml_encode(field)
       << "\" tracktype=\"" << xml_encode(tracktype)
       << "\" occurrence=\"" << (occurrence.size() ? xml_encode(occurrence) : "*")
       << "\" operator=\"" << xml_encode(operand)
       << "\" xpath=\"" << xpath << "\"";
    if (!this->level.empty())
        ss << " level=\"" << xml_encode(this->level) << "\"";
    if (result()>RESULT_PASS || verbose)
        ss << " requested=\""
           << (source && source->values.size() ? xml_encode(source->values.begin()->second) : xml_encode(requested))
           << "\" actual=\"" << xml_encode(value_str) << "\"";
    ss << " outcome=\"" << outcome_str << "\"";

    if (source)
    {
        ss << ">" << std::endl;

        ss << indent(level +1) << "<source";
        if (!source->scope.empty())
            ss << " scope=\"" << xml_encode(source->scope) << "\"";
        ss << " value=\"" << xml_encode(source->field)
           << "\" tracktype=\"" << xml_encode(source->tracktype)
           << "\" occurrence=\"" << (source->occurrence.size() ? xml_encode(source->occurrence) : "*")
           << "\"/>" << std::endl;

        ss << indent(level) << "</rule>" << std::endl;
    }
    else
        ss << "/>" << std::endl;

    return ss.str();
}

//---------------------------------------------------------------------------
// PolicyChecker
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
PolicyChecker::PolicyChecker() : supported(true), full(false)
{
}

//---------------------------------------------------------------------------
PolicyChecker::~PolicyChecker()
{
    while (policies.size())
    {
        delete policies.back();
        policies.pop_back();
    }
}

//---------------------------------------------------------------------------
bool PolicyChecker::is_policy_supported()
{
    return supported;
}


//---------------------------------------------------------------------------
bool PolicyChecker::full_parse()
{
    return full;
}

//---------------------------------------------------------------------------
PolicyChecker::RuleElement* PolicyChecker::parse_rule(tfsxml_string& tfsxml_priv)
{
    RuleElement* rule=new RuleElement();

    tfsxml_string attribute_name;
    tfsxml_string attribute_value;
    while (!tfsxml_attr(&tfsxml_priv, &attribute_name, &attribute_value))
    {
        if (!tfsxml_strcmp_charp(attribute_name, "name"))
            rule->name=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "scope"))
            rule->scope=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "level"))
            rule->level=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "value"))
            rule->field=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "tracktype"))
            rule->tracktype=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "occurrence"))
            rule->occurrence=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "operator"))
            rule->operand=tfsxml_decode(attribute_value);
    }

    if (!tfsxml_hasvalue(&tfsxml_priv))
    {
        tfsxml_string value;
        if (!tfsxml_value(&tfsxml_priv, &value))
            rule->requested = std::string(value.buf, value.len);
    }
    else
    {
        if (!tfsxml_enter(&tfsxml_priv))
        {
            tfsxml_string value;
            while (!tfsxml_next(&tfsxml_priv, &value))
            {
                if (!tfsxml_strcmp_charp(value, "source"))
                {
                    if (rule->source)
                        delete rule->source;
                    rule->source = new RuleElement::Source();
                    while (!tfsxml_attr(&tfsxml_priv, &attribute_name, &attribute_value))
                    {
                        if (!tfsxml_strcmp_charp(attribute_name, "scope"))
                            rule->source->scope=tfsxml_decode(attribute_value);
                        else if (!tfsxml_strcmp_charp(attribute_name, "value"))
                            rule->source->field=tfsxml_decode(attribute_value);
                        else if (!tfsxml_strcmp_charp(attribute_name, "tracktype"))
                            rule->source->tracktype=tfsxml_decode(attribute_value);
                        else if (!tfsxml_strcmp_charp(attribute_name, "occurrence"))
                            rule->source->occurrence=tfsxml_decode(attribute_value);
                    }

                    // Check for currently unsupported features
                    if (rule->scope=="mmt")
                        supported=false;

                    if (rule->scope.empty() || rule->scope=="mi")
                    {
                        std::stringstream ss;
                        ss << "mi:MediaInfo/mi:track[@type='"
                           << rule->source->tracktype << "']["
                           << ((rule->source->occurrence.empty() || rule->source->occurrence=="all" || rule->source->occurrence=="any") ? "*" : rule->source->occurrence)
                           << "]"
                           << tokenize(rule->source->scope, rule->source->field, "/");
                        rule->source->path=parse_path(ss.str());
                    }
                    break;
                }
            }
            tfsxml_leave(&tfsxml_priv);
        }
    }

    // Check for presence of _StringX or TimeCode* element in policy
    size_t index=rule->field.find_last_not_of("0123456789");
    if ((index!=std::string::npos && index>=6 && rule->field.substr(index-6, 7)=="_String") || rule->field.find("TimeCode")==0 || rule->field.rfind("_Total")==rule->field.size()-6)
        full=true;

    // Check for currently unsupported features
    if (rule->scope=="mmt" || rule->requested =="compare")
        supported=false;

    if (rule->scope.empty() || rule->scope=="mi")
    {
        std::stringstream ss;
        ss << "mi:MediaInfo/mi:track[@type='"
           << rule->tracktype
           << "']["
           << ((rule->occurrence.empty() || rule->occurrence=="all" || rule->occurrence=="any") ? "*" : rule->occurrence)
           << "]" << tokenize(rule->scope, rule->field, "/");
        rule->xpath=ss.str();
        rule->path=parse_path(rule->xpath);
    }

    rules.push_back(rule);

    return rule;
}

//---------------------------------------------------------------------------
PolicyChecker::PolicyElement* PolicyChecker::parse_policy(tfsxml_string& tfsxml_priv)
{
    PolicyElement* policy=new PolicyElement();

    tfsxml_string attribute_name;
    tfsxml_string attribute_value;
    while (!tfsxml_attr(&tfsxml_priv, &attribute_name, &attribute_value))
    {
        if (!tfsxml_strcmp_charp(attribute_name, "name"))
            policy->name=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "type"))
            policy->type=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "level"))
            policy->level=tfsxml_decode(attribute_value);
        else if (!tfsxml_strcmp_charp(attribute_name, "version"))
            policy->version=tfsxml_decode(attribute_value);
    }

   tfsxml_string result;
    if (!tfsxml_enter(&tfsxml_priv))
    {
        while (!tfsxml_next(&tfsxml_priv, &result))
        {
            if (!tfsxml_strcmp_charp(result, "description"))
            {
                tfsxml_string result;
                if (!tfsxml_value(&tfsxml_priv, &result))
                    policy->description=std::string(result.buf, result.len);
            }
            else if (!tfsxml_strcmp_charp(result, "tag"))
            {
                tfsxml_string result;
                if (!tfsxml_value(&tfsxml_priv, &result))
                    policy->tags.push_back(std::string(result.buf, result.len));
            }
            else if (!tfsxml_strcmp_charp(result, "policy"))
                policy->children.push_back(parse_policy(tfsxml_priv));
            else if (!tfsxml_strcmp_charp(result, "rule"))
                policy->children.push_back(parse_rule(tfsxml_priv));
        }
    }

    return policy;
}

//---------------------------------------------------------------------------
void PolicyChecker::add_policy(const std::string& policy)
{
    tfsxml_string tfsxml_priv;
    tfsxml_string result;

    tfsxml_init(&tfsxml_priv, (const void*)policy.c_str(), policy.size(), 0);
    while (!tfsxml_next(&tfsxml_priv, &result))
    {
        if (!tfsxml_strcmp_charp(result, "policy"))
        {
            PolicyElement* p=parse_policy(tfsxml_priv);
            if(p)
                policies.push_back(p);
            break;
        }
    }
}

//---------------------------------------------------------------------------
void PolicyChecker::parse_node(tfsxml_string& tfsxml_priv, std::vector<RuleElement*> rules, std::vector<RuleElement*> sources, size_t level)
{
    if (rules.empty() && sources.empty())
        return;

    if (!tfsxml_enter(&tfsxml_priv))
    {
        std::map<PathElement*, size_t> occurrences;

        tfsxml_string result;
        while (!tfsxml_next(&tfsxml_priv, &result))
        {
            const char* id = result.buf;
            std::vector<RuleElement*> matching_rules;
            std::vector<RuleElement*> matching_sources;
            for (size_t pos = 0; pos < rules.size(); pos++)
            {
                if (level < rules[pos]->path.size() && path_is_matching(tfsxml_priv, result, rules[pos]->path[level], occurrences[&rules[pos]->path[level]]))
                {
                    if (level == 1 && (rules[pos]->scope.empty() || rules[pos]->scope == "mi")) // at track level
                        rules[pos]->tracks++;

                    if (level == rules[pos]->path.size() - 1)
                    {
                        tfsxml_string tfsxml_priv_copy = tfsxml_priv;
                        tfsxml_string value;
                        if (!tfsxml_value(&tfsxml_priv_copy, &value))
                            rules[pos]->values[id] = std::string(value.buf, value.len);
                    }
                    else
                        matching_rules.push_back(rules[pos]);
                }
            }

            for (size_t pos = 0; pos < sources.size(); pos++)
            {
                if (sources[pos]->source && level < sources[pos]->source->path.size() && path_is_matching(tfsxml_priv, result, sources[pos]->source->path[level], occurrences[&sources[pos]->source->path[level]]))
                {
                    if (level == sources[pos]->source->path.size() - 1)
                    {
                        tfsxml_string tfsxml_priv_copy = tfsxml_priv;
                        tfsxml_string value;
                        if (!tfsxml_value(&tfsxml_priv_copy, &value))
                            sources[pos]->source->values[id] = std::string(value.buf, value.len);
                    }
                    else
                        matching_sources.push_back(sources[pos]);
                }
            }

            if (!matching_rules.empty() || !matching_sources.empty())
                parse_node(tfsxml_priv, matching_rules, matching_sources, level + 1);
        }
    }
}

//---------------------------------------------------------------------------
int PolicyChecker::analyze(const std::string& report, bool verbose, std::string& out)
{
    std::stringstream ss;
    size_t level=0;
    bool creating_library_present=false;

    ss << indent(level++) << "<MediaConch xmlns=\"https://mediaarea.net/mediaconch\" xmlns:mmt=\"https://mediaarea.net/micromediatrace\" xmlns:mi=\"https://mediaarea.net/mediainfo\" version=\"0.3\">" << std::endl;
    ss << indent(level  ) << "<creatingApplication version=\"" MEDIACONCH_VERSION "\" url=\"https://mediaarea.net/MediaConch\">MediaConch</creatingApplication>" << std::endl;
    tfsxml_string tfsxml_priv;
    tfsxml_string result;
    tfsxml_init(&tfsxml_priv, (const void*)report.c_str(), report.size(), 0);
    while (!tfsxml_next_named(&tfsxml_priv, &result, "MediaArea"))
    {
        if (!tfsxml_enter(&tfsxml_priv))
        {
            while (!tfsxml_next(&tfsxml_priv, &result))
            {
                if (!tfsxml_strcmp_charp(result, "media"))
                {
                    std::string media;
                    tfsxml_string attribute_name;
                    tfsxml_string attribute_value;
                    while (!tfsxml_attr(&tfsxml_priv, &attribute_name, &attribute_value))
                    {
                        if (!tfsxml_strcmp_charp(attribute_name, "ref"))
                            media=std::string(attribute_value.buf, attribute_value.len);
                    }

                    ss << indent(level++) << "<media ref=\"" << media << "\">" << std::endl;
                    parse_node(tfsxml_priv, rules, rules, 0);
                    for (size_t pos=0; pos<policies.size(); pos++)
                        ss << policies[pos]->to_string(level, verbose);
                    ss << indent(--level) << "</media>" << std::endl;

                    // reset states
                    for (size_t pos=0; pos < rules.size(); pos++)
                        rules[pos]->reset();
                }
                else if (!creating_library_present && !tfsxml_strcmp_charp(result, "creatingLibrary"))
                {
                    ss << indent(level) << "<creatingLibrary";

                    tfsxml_string attribute_name, attribute_value, content;
                    while (!tfsxml_attr(&tfsxml_priv, &attribute_name, &attribute_value))
                    {
                       ss << " " << attribute_name;
                        if (attribute_value.len)
                            ss << "=\"" << attribute_value << "\"";
                    }

                    if (!tfsxml_value(&tfsxml_priv, &content))
                        ss << ">" << content << "</creatingLibrary>";
                    else
                        ss << "/>";
                    ss << std::endl;

                    creating_library_present=true;
                }
            }
        }
    }
    ss << indent(--level) << "</MediaConch>" << std::endl;

    out = ss.str();
    return 0;
}

}

#ifdef __EMSCRIPTEN__
#include <emscripten/bind.h>
EMSCRIPTEN_BINDINGS(mediaconch_policychecker) {
    emscripten::class_<MediaConch::PolicyChecker>("PolicyChecker")
        .constructor()
        .function("is_policy_supported", &MediaConch::PolicyChecker::is_policy_supported)
        .function("full_parse", &MediaConch::PolicyChecker::full_parse)
        .function("add_policy", &MediaConch::PolicyChecker::add_policy)
        .function("analyze", emscripten::optional_override([](MediaConch::PolicyChecker& self, const std::string& report, bool verbose) {
            std::string out;
            self.MediaConch::PolicyChecker::analyze(report, verbose, out);

            return out;
        }))
    ;
}
#endif //__EMSCRIPTEN__