File: accessunit.c

package info (click to toggle)
tstools 1.13~git20151030-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, trixie
  • size: 2,916 kB
  • sloc: ansic: 37,970; java: 2,243; makefile: 466; python: 319; sh: 5
file content (1436 lines) | stat: -rw-r--r-- 47,360 bytes parent folder | download | duplicates (3)
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
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
/*
 * Utilities for working with access units in H.264 elementary streams.
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the MPEG TS, PS and ES tools.
 *
 * The Initial Developer of the Original Code is Amino Communications Ltd.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Amino Communications Ltd, Swavesey, Cambridge UK
 *
 * ***** END LICENSE BLOCK *****
 */

#include <stdio.h>
#include <stdlib.h>

#include "compat.h"
#include "printing_fns.h"
#include "es_fns.h"
#include "ts_fns.h"
#include "nalunit_fns.h"
#include "accessunit_fns.h"
#include "reverse_fns.h"

#define DEBUG 0


/*
 * Build a new access unit datastructure.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static inline int build_access_unit(access_unit_p  *acc_unit,
                                    uint32_t        index)
{
  int err;

  access_unit_p  new = malloc(SIZEOF_ACCESS_UNIT);
  if (new == NULL)
  {
    print_err("### Unable to allocate access unit datastructure\n");
    return 1;
  }

  err = build_nal_unit_list(&(new->nal_units));
  if (err)
  {
    free(new);
    *acc_unit = NULL;
    return err;
  }
  new->index = index;
  new->started_primary_picture = FALSE;
  new->primary_start = NULL;
  new->ignored_broken_NAL_units = 0;

  new->frame_num = new->field_pic_flag = new->bottom_field_flag = 0;

  *acc_unit = new;
  return 0;
}

/*
 * Tidy up an access unit datastructure after we've finished with it.
 *
 * If `deep` is TRUE, also frees all of the NAL units in the NAL unit
 * list (which is normally what we want to do).
 */
static inline void clear_access_unit(access_unit_p  acc_unit,
                                     int            deep)
{
  free_nal_unit_list(&(acc_unit->nal_units),deep);
  acc_unit->primary_start = NULL;
}

/*
 * Tidy up and free an access unit datastructure after we've finished with it.
 *
 * Clears the datastructure, frees it, and returns `acc_unit` as NULL.
 *
 * Does nothing if `acc_unit` is already NULL.
 */
extern void free_access_unit(access_unit_p  *acc_unit)
{
  if (*acc_unit == NULL)
    return;
  clear_access_unit(*acc_unit,TRUE);
  free(*acc_unit);
  *acc_unit = NULL;
}

/*
 * Report on this access unit
 */
extern void report_access_unit(access_unit_p  access_unit)
{
  int ii;
  fprint_msg("Access unit %u",access_unit->index);
  if (access_unit->started_primary_picture)
    fprint_msg(" (%s)",access_unit->primary_start->start_reason);
  print_msg(":\n");
  if (access_unit->field_pic_flag)
    fprint_msg("  %s field of frame %u\n",
               (access_unit->bottom_field_flag==1?"Bottom":"Top"),
               access_unit->frame_num);
  else
    fprint_msg("  Frame %u\n",access_unit->frame_num);

  if (access_unit->ignored_broken_NAL_units)
    fprint_msg("  Ignored %d broken NAL unit%s\n",
               access_unit->ignored_broken_NAL_units,
               (access_unit->ignored_broken_NAL_units==1?"":"s"));
  
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p nal = access_unit->nal_units->array[ii];
    if (nal == NULL)
      print_msg("     <null>\n");
    else
    {
      fprint_msg("    %c",((access_unit->primary_start == nal)?'*':' '));
      report_nal(TRUE,nal);
    }
  }
}

/*
 * How many slices (VCL NAL units) are there in this access unit?
 */
static inline int num_slices(access_unit_p  access_unit)
{
  int count = 0;
  int ii;
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    if (nal_is_slice(access_unit->nal_units->array[ii]))
      count ++;
  }
  return count;
}

/*
 * Retrieve the bounds of this access unit in the file it was read from.
 *
 * - `access_unit` is the access unit we're interested in
 * - `start` is its start position (i.e., the location at which to start
 *   reading to retrieve all of the data for the access unit, including
 *   the 00 00 01 prefix at the start of the first NAL unit therein)
 * - `length` is the total length of the NAL units within this access unit
 *
 * Returns 0 if all goes well, 1 if the access unit has no content.
 */
extern int get_access_unit_bounds(access_unit_p     access_unit,
                                  ES_offset        *start,
                                  uint32_t         *length)
{
  int ii;
  if (access_unit->primary_start == NULL)
  {
    print_err("### Cannot determine bounds of an access unit with no content\n");
    return 1;
  }

  *start = access_unit->nal_units->array[0]->unit.start_posn;
  *length = 0;

  // Maybe we should precalculate, or even cache, the total length...
  for (ii=0; ii<access_unit->nal_units->length; ii++)
    (*length) += access_unit->nal_units->array[ii]->unit.data_len;

  return 0;
}

/*
 * Are all slices in this access unit I slices?
 */
extern int all_slices_I(access_unit_p  access_unit)
{
  int ii;
  if (access_unit->primary_start == NULL)
    return FALSE;
  if (!nal_is_slice(access_unit->primary_start))
    return FALSE;
  // All I
  if (access_unit->primary_start->u.slice.slice_type == ALL_SLICES_I)
    return TRUE;
  // Only one slice, and it's I
  if (num_slices(access_unit) == 1 &&
      access_unit->primary_start->u.slice.slice_type == SLICE_I)
    return TRUE;
  // Are any of the slices not I?
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal_unit = access_unit->nal_units->array[ii];
    if (nal_is_slice(nal_unit) && nal_unit->u.slice.slice_type != SLICE_I)
      return FALSE;
  }
  return TRUE;
}

/*
 * Are all slices in this access unit P slices?
 */
extern int all_slices_P(access_unit_p  access_unit)
{
  int ii;
  if (access_unit->primary_start == NULL)
    return FALSE;
  if (!nal_is_slice(access_unit->primary_start))
    return FALSE;
  // All P
  if (access_unit->primary_start->u.slice.slice_type == ALL_SLICES_P)
    return TRUE;
  // Only one slice, and it's P
  if (num_slices(access_unit) == 1 &&
      access_unit->primary_start->u.slice.slice_type == SLICE_P)
    return TRUE;
  // Are any of the slices not P?
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal_unit = access_unit->nal_units->array[ii];
    if (nal_is_slice(nal_unit) && nal_unit->u.slice.slice_type != SLICE_P)
      return FALSE;
  }
  return TRUE;
}

/*
 * Are all slices in this access unit I or P slices?
 */
extern int all_slices_I_or_P(access_unit_p  access_unit)
{
  int ii;
  if (access_unit->primary_start == NULL)
    return FALSE;
  if (!nal_is_slice(access_unit->primary_start))
    return FALSE;
  // All P or all I
  if (access_unit->primary_start->u.slice.slice_type == SLICE_I ||
      access_unit->primary_start->u.slice.slice_type == SLICE_P)
    return TRUE;
  // Only one slice, and it's P or I
  if (num_slices(access_unit) == 1 &&
      (access_unit->primary_start->u.slice.slice_type == ALL_SLICES_I ||
       access_unit->primary_start->u.slice.slice_type == ALL_SLICES_P))
    return TRUE;
  // Are any of the slices not either P or I?
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal_unit = access_unit->nal_units->array[ii];
    if (nal_is_slice(nal_unit) &&
        (nal_unit->u.slice.slice_type != SLICE_I &&
         nal_unit->u.slice.slice_type != SLICE_P))
      return FALSE;
  }
  return TRUE;
}

/*
 * Are all slices in this access unit B slices?
 */
extern int all_slices_B(access_unit_p  access_unit)
{
  int ii;
  if (access_unit->primary_start == NULL)
    return FALSE;
  if (!nal_is_slice(access_unit->primary_start))
    return FALSE;
  // All B
  if (access_unit->primary_start->u.slice.slice_type == ALL_SLICES_B)
    return TRUE;
  // Only one slice, and it's B
  if (num_slices(access_unit) == 1 &&
      access_unit->primary_start->u.slice.slice_type == SLICE_B)
    return TRUE;
  // Are any of the slices not B?
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal_unit = access_unit->nal_units->array[ii];
    if (nal_is_slice(nal_unit) && nal_unit->u.slice.slice_type != SLICE_B)
      return FALSE;
  }
  return TRUE;
}

/*
 * Append a NAL unit to the list of NAL units for this access unit
 *
 * NB: `pending` may be NULL
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int access_unit_append(access_unit_p    access_unit,
                              nal_unit_p       nal,
                              int              starts_primary,
                              nal_unit_list_p  pending)
{
  int err;
  if (starts_primary && access_unit->started_primary_picture)
  {
    // Our caller should have started a new access unit instead
    fprint_err("### Already had a start of primary picture in access"
               " unit %d\n",access_unit->index);
    return 1;
  }

  if (starts_primary)
  {
    access_unit->primary_start = nal;
    access_unit->started_primary_picture = TRUE;
    access_unit->frame_num = nal->u.slice.frame_num;
    access_unit->field_pic_flag = nal->u.slice.field_pic_flag;
    access_unit->bottom_field_flag = nal->u.slice.bottom_field_flag;
  }
  if (pending != NULL && pending->length > 0)
  {
    int ii;
    for (ii=0; ii<pending->length; ii++)
    {
      err = append_to_nal_unit_list(access_unit->nal_units,
                                    pending->array[ii]);
      if (err)
      {
        fprint_err("### Error extending access unit %d\n",
                   access_unit->index);
        return err;
      }
    }
  }

  if (nal != NULL)
  {
    err = append_to_nal_unit_list(access_unit->nal_units,nal);
    if (err)
    {
      fprint_err("### Error extending access unit %d\n",
                 access_unit->index);
      return err;
    }
  }
  return 0;
}

/*
 * Merge the NAL units of the second access unit into the first, and then
 * free the second access unit.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int merge_access_unit_nals(access_unit_p   access_unit1,
                                  access_unit_p  *access_unit2)
{
  int  err, ii;

  for (ii = 0; ii < (*access_unit2)->nal_units->length; ii++)
  {
    err = append_to_nal_unit_list(access_unit1->nal_units,
                                  (*access_unit2)->nal_units->array[ii]);
    if (err)
    {
      print_err("### Error merging two access units\n");
      return err;
    }
  }

  // Don't forget that we're now "sharing" any ignored NAL units
  access_unit1->ignored_broken_NAL_units +=
    (*access_unit2)->ignored_broken_NAL_units;

  // Take care not to free the individual NAL units in our second access
  // unit, as they are still being used by the first
  clear_access_unit(*access_unit2,FALSE);
  free(*access_unit2);
  *access_unit2 = NULL;

  // Fake the flags in our remaining access unit to make us "look" like
  // a frame
  access_unit1->field_pic_flag = 0;
  return 0;
}

/*
 * Write out an access unit as ES.
 *
 * Also writes out any end of sequence or end of stream NAL unit found in the
 * `context` (since they are assumed to have immediately followed this access
 * unit).
 *
 * - `access_unit` is the access unit to write out
 * - `context` may contain additional things to write (see above), but may
 *   legitimately be NULL if there is no context.
 * - `output` is the ES file to write to
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
extern int write_access_unit_as_ES(access_unit_p           access_unit,
                                   access_unit_context_p   context,
                                   FILE                   *output)
{
  int ii, err;
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    err = write_ES_unit(output,&(access_unit->nal_units->array[ii]->unit));
    if (err)
    {
      print_err("### Error writing NAL unit ");
      report_nal(FALSE,access_unit->nal_units->array[ii]);
      return err;
    }
  }

  if (context != NULL && context->end_of_sequence)
  {
    err = write_ES_unit(output,&(context->end_of_sequence->unit));
    if (err)
    {
      print_err("### Error writing end of sequence NAL unit ");
      report_nal(FALSE,context->end_of_sequence);
      return err;
    }
    free_nal_unit(&context->end_of_sequence);
  }

  if (context != NULL && context->end_of_stream)
  {
    err = write_ES_unit(output,&(context->end_of_stream->unit));
    if (err)
    {
      print_err("### Error writing end of stream NAL unit ");
      report_nal(FALSE,context->end_of_sequence);
      return err;
    }
    free_nal_unit(&context->end_of_stream);
  }
  return 0;
}

/*
 * Write out the (potential) trailing components of an access unit as TS.
 *
 * I.e., writes out any end of sequence or end of stream NAL unit found in the
 * `context` (since they are assumed to have immediately followed this access
 * unit).
 *
 * - `context` may contain additional things to write (see above), but may
 *   legitimately be NULL if there is no context.
 * - `tswriter` is the TS context to write with
 * - `video_pid` is the PID to use to write the data
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int write_access_unit_trailer_as_TS(access_unit_context_p  context,
                                           TS_writer_p            tswriter,
                                           uint32_t               video_pid)
{
  int err;

  if (context != NULL && context->end_of_sequence)
  {
    nal_unit_p  nal = context->end_of_sequence;
    err = write_ES_as_TS_PES_packet(tswriter,nal->unit.data,nal->unit.data_len,
                                    video_pid,DEFAULT_VIDEO_STREAM_ID);
    if (err)
    {
      print_err("### Error writing end of sequence NAL unit ");
      report_nal(FALSE,nal);
      return err;
    }
    free_nal_unit(&context->end_of_sequence);
  }

  if (context != NULL && context->end_of_stream)
  {
    nal_unit_p  nal = context->end_of_stream;
    err = write_ES_as_TS_PES_packet(tswriter,nal->unit.data,nal->unit.data_len,
                                    video_pid,DEFAULT_VIDEO_STREAM_ID);
    if (err)
    {
      print_err("### Error writing end of stream NAL unit ");
      report_nal(FALSE,nal);
      return err;
    }
    free_nal_unit(&context->end_of_stream);
  }
  return 0;
}

/*
 * Write out an access unit as TS.
 *
 * Also writes out any end of sequence or end of stream NAL unit found in the
 * `context` (since they are assumed to have immediately followed this access
 * unit).
 *
 * - `access_unit` is the access unit to write out
 * - `context` may contain additional things to write (see above), but may
 *   legitimately be NULL if there is no context.
 * - `tswriter` is the TS context to write with
 * - `video_pid` is the PID to use to write the data
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
extern int write_access_unit_as_TS(access_unit_p          access_unit,
                                   access_unit_context_p  context,
                                   TS_writer_p            tswriter,
                                   uint32_t               video_pid)
{
  int ii, err;
  
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal = access_unit->nal_units->array[ii];

    err = write_ES_as_TS_PES_packet(tswriter,
                                    nal->unit.data,nal->unit.data_len,
                                    video_pid,DEFAULT_VIDEO_STREAM_ID);
    if (err)
    {
      print_err("### Error writing NAL unit ");
      report_nal(FALSE,nal);
      return err;
    }
  }
  return write_access_unit_trailer_as_TS(context,tswriter,video_pid);
}

/*
 * Write out an access unit as TS, with PTS timing in the first PES packet
 * (and PCR timing in the first TS of the frame).
 *
 * Also writes out any end of sequence or end of stream NAL unit found in the
 * `context` (since they are assumed to have immediately followed this access
 * unit).
 *
 * - `access_unit` is the access unit to write out
 * - `context` may contain additional things to write (see above), but may
 *   legitimately be NULL if there is no context.
 * - `tswriter` is the TS context to write with
 * - `video_pid` is the PID to use to write the data
 * - `got_pts` is TRUE if we have a PTS value, in which case
 * - `pts` is said PTS value
 * - `got_dts` is TRUE if we also have DTS, in which case
 * - `dts` is said DTS value.
 *
 * If we are given a DTS (which must, by definition, always go up) we will also
 * use it as the value for PCR.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
extern int write_access_unit_as_TS_with_pts_dts(access_unit_p          access_unit,
                                                access_unit_context_p  context,
                                                TS_writer_p            tswriter,
                                                uint32_t               video_pid,
                                                int                    got_pts,
                                                uint64_t               pts,
                                                int                    got_dts,
                                                uint64_t               dts)
{
  int ii, err;
  
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal = access_unit->nal_units->array[ii];

    // Only write the first PES packet out with PTS
    if (ii == 0)
      err = write_ES_as_TS_PES_packet_with_pts_dts(tswriter,
                                                   nal->unit.data,
                                                   nal->unit.data_len,
                                                   video_pid,
                                                   DEFAULT_VIDEO_STREAM_ID,
                                                   got_pts,pts,
                                                   got_dts,dts);
    else
      err = write_ES_as_TS_PES_packet(tswriter,
                                      nal->unit.data,nal->unit.data_len,
                                      video_pid,DEFAULT_VIDEO_STREAM_ID);
    if (err)
    {
      print_err("### Error writing NAL unit ");
      report_nal(FALSE,nal);
      return err;
    }
  }
  return write_access_unit_trailer_as_TS(context,tswriter,video_pid);
}

/*
 * Write out an access unit as TS, with PCR timing in the first TS of the
 * frame.
 *
 * Also writes out any end of sequence or end of stream NAL unit found in the
 * `context` (since they are assumed to have immediately followed this access
 * unit).
 *
 * - `access_unit` is the access unit to write out
 * - `context` may contain additional things to write (see above), but may
 *   legitimately be NULL if there is no context.
 * - `tswriter` is the TS context to write with
 * - `video_pid` is the PID to use to write the data
 * - `pcr_base` and `pcr_extn` encode the PCR value.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
extern int write_access_unit_as_TS_with_PCR(access_unit_p          access_unit,
                                            access_unit_context_p  context,
                                            TS_writer_p            tswriter,
                                            uint32_t               video_pid,
                                            uint64_t               pcr_base,
                                            uint32_t               pcr_extn)
{
  int ii, err;
  
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    nal_unit_p  nal = access_unit->nal_units->array[ii];

    // Only write the first PES packet out with PCR
    if (ii == 0)
      err = write_ES_as_TS_PES_packet_with_pcr(tswriter,
                                               nal->unit.data,
                                               nal->unit.data_len,
                                               video_pid,
                                               DEFAULT_VIDEO_STREAM_ID,
                                               pcr_base,pcr_extn);
    else
      err = write_ES_as_TS_PES_packet(tswriter,
                                      nal->unit.data,nal->unit.data_len,
                                      video_pid,DEFAULT_VIDEO_STREAM_ID);
    if (err)
    {
      print_err("### Error writing NAL unit ");
      report_nal(FALSE,nal);
      return err;
    }
  }
  return write_access_unit_trailer_as_TS(context,tswriter,video_pid);
}

/*
 * End this access unit.
 *
 * - `access_unit` is the access unit to end.
 * - if `show_details` is true, then a summary of its contents is printed
 *   out.
 *
 * Actually, with the current code scheme, this only does much if
 * `show_details` is true. However, it may still be a useful hook
 * for actual work later on.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static inline int end_access_unit(access_unit_context_p context,
                                  access_unit_p         access_unit,
                                  int                   show_details)
{
  if (show_details)
  {
    report_access_unit(access_unit);
    if (context->pending_nal)
    {
      print_msg("... pending: ");
      report_nal(TRUE,context->pending_nal);
    }
    if (context->end_of_sequence)
    {
      print_msg("--> EndOfSequence ");
      report_nal(TRUE,context->end_of_sequence);
    }
    if (context->end_of_stream)
    {
      print_msg("--> EndOfStream ");
      report_nal(TRUE,context->end_of_stream);
    }
  }
  return 0;
}

/*
 * Build a new access unit context datastructure.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
extern int build_access_unit_context(ES_p                   es,
                                     access_unit_context_p *context)
{
  int err;
  access_unit_context_p  new = malloc(SIZEOF_ACCESS_UNIT_CONTEXT);
  if (new == NULL)
  {
    print_err("### Unable to allocate access unit context datastructure\n");
    return 1;
  }

  new->pending_nal = NULL;
  new->end_of_stream = NULL;
  new->end_of_sequence = NULL;
  new->access_unit_index = 0;
  new->reverse_data = NULL;
  new->no_more_data = FALSE;
  new->earlier_primary_start = NULL;

  err = build_nal_unit_context(es,&new->nac);
  if (err)
  {
    print_err("### Error building access unit context datastructure\n");
    free(new);
    return err;
  }
  err = build_nal_unit_list(&new->pending_list);
  if (err)
  {
    print_err("### Error building access unit context datastructure\n");
    free_nal_unit_context(&new->nac);
    free(new);
    return err;
  }

  *context = new;
  return 0;
}

/*
 * Free a new access unit context datastructure.
 *
 * Clears the datastructure, frees it, and returns `context` as NULL.
 *
 * Does not free any `reverse_data` datastructure.
 *
 * Does nothing if `context` is already NULL.
 */
extern void free_access_unit_context(access_unit_context_p *context)
{
  access_unit_context_p  cc = *context;

  if (cc == NULL)
    return;

  // We assume no-one else has an interest in the NAL units in
  // our "pending" list.
  free_nal_unit_list(&cc->pending_list,TRUE);

  // And similarly, we should be the only "person" holding on to these
  free_nal_unit(&cc->earlier_primary_start); // although this is bluff
  free_nal_unit(&cc->end_of_sequence);
  free_nal_unit(&cc->end_of_stream);
  free_nal_unit(&cc->pending_nal);

  free_nal_unit_context(&cc->nac);

  cc->reverse_data = NULL;
  
  free(*context);
  *context = NULL;
  return;
}

/*
 * Reset an acccess unit context, so it "forgets" its current information
 * about what it is reading, etc.
 */
extern void reset_access_unit_context(access_unit_context_p  context)
{
  free_nal_unit(&context->earlier_primary_start);
  free_nal_unit(&context->end_of_sequence);
  free_nal_unit(&context->end_of_stream);
  free_nal_unit(&context->pending_nal);
  reset_nal_unit_list(context->pending_list,FALSE); // @@@ leak???
  context->no_more_data = FALSE;
  // We have to hope that the "previous" sequence parameter and picture
  // parameter dictionaries are still applicable, since we don't still
  // have a record of the ones that would have been in effect at this
  // point.
}

/*
 * Rewind a file being read as access units.
 *
 * This is a wrapper for `rewind_nal_unit_context` that also knows to
 * unset things appropriate to the access unit context.
 *
 * If a reverse context is attached to this access unit, it also will
 * be "rewound" appropriately.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int rewind_access_unit_context(access_unit_context_p  context)
{
  // First, forget where we are
  reset_access_unit_context(context);

  context->access_unit_index = 0;  // no access units read from this file yet

  // Next, take care of rewinding
  if (context->reverse_data)
  {
    context->reverse_data->last_posn_added = -1; // next entry to be 0
  }

  // And then, do the relocation itself
  return rewind_nal_unit_context(context->nac);
}

/*
 * Remember the required information from the previous access unit's
 * first VLC NAL unit (i.e., the one that starts its primary picture).
 *
 * If we just remembered the (address of the) NAL unit itself, we would
 * have a problem if/when the access unit containing it was freed, since
 * that would also free the NAL unit. Luckily, the information we want
 * to remember is well defined, and does not require us to do anything
 * other than copy data, so we can reuse the same "internal" NAL unit
 * without needing to do lots of mallocing around.
 *
 * It *should* be obvious, given its intended use, but do not call this
 * on a NAL unit that has not been decoded - things may fall apart
 * messily later on...
 *
 * (NB: the "pseudo" NAL unit we use to remember the information is
 * a true NAL unit except for not having any of the data/rbsp arrays
 * filled in, so it *does* cause the NAL unit id to be incremented,
 * which has confused me at least once when reading diagnostic output.)
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int remember_earlier_primary_start(access_unit_context_p context,
                                          nal_unit_p            nal)
{
  nal_unit_p  tgt = context->earlier_primary_start;

  if (tgt == NULL)
  {
    int err = build_nal_unit(&tgt);
    if (err)
    {
      print_err("### Error building NAL unit for 'earlier primary start'\n");
      free(tgt);
      return err;
    }
    context->earlier_primary_start = tgt;
  }
  
  tgt->starts_picture_decided = nal->starts_picture_decided;
  tgt->starts_picture = nal->starts_picture;
  tgt->start_reason = nal->start_reason;
  tgt->decoded = nal->decoded;

  tgt->nal_ref_idc = nal->nal_ref_idc;
  tgt->nal_unit_type = nal->nal_unit_type;
  tgt->u = nal->u;

  // Lastly, we may not need the following, but they are sufficient to
  // allow us to read the whole NAL unit back in if we should need to.
  tgt->unit.start_posn = nal->unit.start_posn;
  tgt->unit.data_len = nal->unit.data_len;
  
  return 0;
}

/*
 * Maybe remember an access unit for reversing - either an IDR or one with all
 * frames I
 */
static int maybe_remember_access_unit(reverse_data_p  reverse_data,
                                      access_unit_p   access_unit,
                                      int             verbose)
{
  // Keep it if it is an IDR, or all of its contents are I slices
  if (access_unit->primary_start != NULL &&
      access_unit->primary_start->nal_ref_idc != 0 &&
      (access_unit->primary_start->nal_unit_type == NAL_IDR ||
       all_slices_I(access_unit)))
  {
    ES_offset  start_posn = {0,0};
    uint32_t   num_bytes = 0;
    int err = get_access_unit_bounds(access_unit,&start_posn,&num_bytes);
    if (err)
    {
      fprint_err("### Error working out position/size of access unit %d"
                 " for reversing\n",access_unit->index);
      return 1;
    }
    err = remember_reverse_h264_data(reverse_data,access_unit->index,
                                     start_posn,num_bytes);
    if (err)
    {
      fprint_err("### Error remembering access unit %d for reversing\n",
                 access_unit->index);
      return 1;
    }
    if (verbose) fprint_msg("REMEMBER IDR %5d at " OFFSET_T_FORMAT_08
                            "/%04d for %5d\n",access_unit->index,
                            start_posn.infile,start_posn.inpacket,num_bytes);
  }
  return 0;
}

/*
 * Retrieve the next access unit from the given elementary stream.
 *
 * - `context` is the context information needed to allow us to find
 *   successive access units.
 * - `quiet` is true if we should try to be silent about it
 * - `show_details` is true if we should output more info than normal
 * - `ret_access_unit` is the next access unit.
 *
 * If the access unit was ended because an end of sequence or end of
 * stream NAL unit was encountered, then said end of sequence/stream
 * NAL unit will be remembered in the `context`.
 *
 * Note that it is possible to get back an *empty* access unit in
 * certain situations - the most obvious of which is if we get two
 * ``end of sequence`` NAL units with nothing betwen them.
 *
 * Because of this possibility, some care should be taken to allow for
 * access units that do not contain a primary picture (no VCL NAL unit),
 * and contain zero NAL units. Also, if one is trying for an accurate
 * count of access units, such instances should probably be ignored.
 *
 * Returns 0 if it succeeds, EOF if there is no more data to read, or 1 if
 * some error occurs.
 *
 * EOF can be returned because the end of file has been reached, or because an
 * end of stream NAL unit has been encountered. The two may be distinguished
 * by looking at `context->end_of_stream`, which will be NULL if it was a true
 * EOF.
 *
 * Note that `ret_access_unit` will be NULL if EOF is returned.
 */
extern int get_next_access_unit(access_unit_context_p context,
                                int                   quiet,
                                int                   show_details,
                                access_unit_p        *ret_access_unit)
{
  int            err;
  nal_unit_p     nal = NULL;
  access_unit_p  access_unit;

  // Is there anything more to read from the input stream?
  if (context->no_more_data)
  {
    *ret_access_unit = NULL;
    return EOF;
  }
  
  // Since we're expecting to return a new access unit,
  // we'd better build it...
  err = build_access_unit(&access_unit,context->access_unit_index+1);
  if (err) return err;

  // Did we have any left over stuff to put at its start?
  if (context->pending_nal != NULL)
  {
    err = access_unit_append(access_unit,
                             context->pending_nal,TRUE,context->pending_list);
    if (err) goto give_up;
    context->pending_nal = NULL;
    reset_nal_unit_list(context->pending_list,FALSE);
  }
  
  for (;;)
  {
    err = find_next_NAL_unit(context->nac,FALSE,&nal);
    if (err == EOF)
    {
      context->no_more_data = TRUE;  // prevent future reads on this stream
      break;
    }
    else if (err == 2)
    {
      // The NAL unit was broken. Should we:
      // a) ignore it and pretend it never happened (i.e., ``continue``)
      // b) ignore it and give up on the current access unit (i.e., unset
      //    our current status, and hunt for the start of the next access
      //    unit).
      // Clearly, option (a) is the easiest to try, so let's see how that
      // works for now...
      print_err("!!! Ignoring broken NAL unit\n");
      access_unit->ignored_broken_NAL_units ++;
      continue;
    }
    else if (err)
    {
      print_err("### Error retrieving next NAL\n");
      goto give_up;
    }
    
    if (nal_is_slice(nal))
    {
      if (!access_unit->started_primary_picture)
      {
        // We're in a new access unit, but we haven't had a slice
        // yet, so we can be lazy and assume that this must be the
        // first slice
        // (What we're *not* checking is whether the first access
        // unit in the bitstream starts with an IDR, which might be
        // a good idea)
        nal->start_reason = "First slice of new access unit";
        err = access_unit_append(access_unit,nal,TRUE,context->pending_list);
        if (err) goto give_up_free_nal;
        reset_nal_unit_list(context->pending_list,FALSE);
        err = remember_earlier_primary_start(context,nal);
        if (err) goto give_up_free_nal;
      }
      else if (nal_is_first_VCL_NAL(nal,context->earlier_primary_start))
      {
        // Regardless of what we determine next, we need to remember that the
        // NAL started (what may later be the previous) access unit
        err = remember_earlier_primary_start(context,nal);
        if (err) goto give_up_free_nal;
        if (access_unit->started_primary_picture)
        {
          // We were already in an access unit with a primary
          // picture, so this NAL unit must start a new access unit.
          // Remember it for next time, and return the access unit so far.
          context->pending_nal = nal;
          break;  // Ready to return the access unit
        }
        else
        {
          // This access unit was waiting for its primary picture
          err = access_unit_append(access_unit,nal,TRUE,context->pending_list);
          if (err) goto give_up_free_nal;
          reset_nal_unit_list(context->pending_list,FALSE);
        }
      }
      else if (!access_unit->started_primary_picture)
      {
        // But this is not a NAL unit that may start a new
        // access unit. So what should we do? Ignore it?
        if (!quiet)
        {
          print_err("!!! Ignoring VCL NAL that cannot start a picture:\n");
          print_err("    ");
          report_nal(FALSE,nal);
          print_err("\n");
        }
        free_nal_unit(&nal);
      }
      else if (nal_is_redundant(nal))
      {
        // pass
        // print_msg("   ignoring redundant NAL unit\n");
        free_nal_unit(&nal);
      }
      else
      {
        // We're part of the same access unit, but not special
        err = access_unit_append(access_unit,nal,FALSE,context->pending_list);
        if (err) goto give_up_free_nal;
        reset_nal_unit_list(context->pending_list,FALSE);
      }
    }
    else if (nal->nal_unit_type == NAL_ACCESS_UNIT_DELIM)
    {
      // We always start an access unit...
      if (access_unit->started_primary_picture)
      {
        err = append_to_nal_unit_list(context->pending_list,nal);
        if (err) goto give_up_free_nal;
        break; // Ready to return the "previous" access unit
      }
      else
      {
        // The current access unit doesn't yet have any VCL NALs
        if (context->pending_list->length > 0 ||
            access_unit->nal_units->length > 0)
        {
          print_err("!!! Ignoring incomplete access unit:\n");
          if (access_unit->nal_units->length > 0)
          {
            report_nal_unit_list(FALSE,"    ",access_unit->nal_units);
            reset_nal_unit_list(access_unit->nal_units,TRUE);
          }
          if (context->pending_list->length > 0)
          {
            report_nal_unit_list(FALSE,"    ",context->pending_list);
            reset_nal_unit_list(context->pending_list,TRUE);
          }
        }
        err = access_unit_append(access_unit,nal,FALSE,NULL);
        if (err) goto give_up_free_nal;
      }
    }
    else if (nal->nal_unit_type == NAL_SEI)
    {
      // SEI units always precede the primary coded picture
      // - so they also implicitly end any access unit that has already
      // started its primary picture
      if (access_unit->started_primary_picture)
      {
        err = append_to_nal_unit_list(context->pending_list,nal);
        if (err) goto give_up_free_nal;
        break; // Ready to return the "previous" access unit
      }
      else
      {
        err = append_to_nal_unit_list(context->pending_list,nal);
        if (err) goto give_up_free_nal;
      }
    }
    else if (nal->nal_unit_type == NAL_SEQ_PARAM_SET || 
             nal->nal_unit_type == NAL_PIC_PARAM_SET ||
             nal->nal_unit_type == 13 ||
             nal->nal_unit_type == 14 ||
             nal->nal_unit_type == 15 ||
             nal->nal_unit_type == 16 ||
             nal->nal_unit_type == 17 ||
             nal->nal_unit_type == 18)
    {
      // These start a new access unit *if* they come after the
      // last VCL NAL of an access unit. But we can only *tell*
      // that they are after the last VCL NAL of an access unit
      // when we start the next access unit (!) - so we need to
      // hold them in hand until we know that we need them.
      // (i.e., they'll get added to an access unit just before
      // the next "more determined" NAL unit we add to an access
      // unit)
      err = append_to_nal_unit_list(context->pending_list,nal);
      if (err) goto give_up_free_nal;
    }
    else if (nal->nal_unit_type == NAL_END_OF_SEQ)
    {
      if (context->pending_list->length > 0)
      {
        print_err("!!! Ignoring items after last VCL NAL and"
                  " before End of Sequence:\n");
        report_nal_unit_list(FALSE,"    ",context->pending_list);
        reset_nal_unit_list(context->pending_list,TRUE);
      }
      // And remember this as the End of Sequence marker
      context->end_of_sequence = nal;
      break;
    }
    else if (nal->nal_unit_type == NAL_END_OF_STREAM)
    {
      if (context->pending_list->length > 0)
      {
        print_err("!!! Ignoring items after last VCL NAL and"
                  " before End of Stream:\n");
        report_nal_unit_list(FALSE,"    ",context->pending_list);
        reset_nal_unit_list(context->pending_list,TRUE);
      }
      // And remember this as the End of Stream marker
      context->end_of_stream = nal;
      // Which means there's no point in reading more from this stream
      // (setting no_more_data like this means that *next* time this
      // function is called, it will return EOF)
      context->no_more_data = TRUE;
      break;
    }
    else
    {
      // It's not a slice, or an access unit delimiter, or an
      // end of sequence or stream, or a sequence or picture
      // parameter set, or various other odds and ends, so it
      // looks like we can ignore it.
      free_nal_unit(&nal);
    }
  }

  // Check for an immediate "end of file with no data"
  // - i.e., we read EOF or end of stream, and there was nothing
  // between the last access unit and such reading
  if (context->no_more_data && access_unit->nal_units->length == 0)
  {
    free_access_unit(&access_unit);
    *ret_access_unit = NULL;
     return EOF;
  }
  
  // Otherwise, finish off and return the access unit we have in hand
  err = end_access_unit(context,access_unit,show_details);
  if (err) goto give_up;

  // Remember to count it
  context->access_unit_index ++;

  *ret_access_unit = access_unit;
  return 0;

give_up_free_nal:
  free_nal_unit(&nal);
give_up:
  free_access_unit(&access_unit);
  return 1;
}

/*
 * Retrieve the next non-empty access unit from the given elementary stream.
 *
 * - `context` is the context information needed to allow us to find
 *   successive access units.
 * - `quiet` is true if we should try to be silent about it
 * - `show_details` is true if we should output more info than normal
 * - `frame` is an access unit datastructure representing the next
 *   frame.
 *
 * If the access unit was ended because an end of sequence or end of
 * stream NAL unit was encountered, then said end of sequence/stream
 * NAL unit will be remembered in the `context`.
 *
 * Returns 0 if it succeeds, EOF if there is no more data to read, or 1 if
 * some error occurs.
 *
 * EOF can be returned because the end of file has been reached, or because an
 * end of stream NAL unit has been encountered. The two may be distinguished
 * by looking at `context->end_of_stream`, which will be NULL if it was a true
 * EOF.
 *
 * Note that `ret_access_unit` will be NULL if EOF is returned.
 */
static int get_next_non_empty_access_unit(access_unit_context_p context,
                                          int                   quiet,
                                          int                   show_details,
                                          access_unit_p        *access_unit)
{
  for (;;)
  {
    int err = get_next_access_unit(context,quiet,show_details,access_unit);
    if (err) return err;

    if ((*access_unit)->primary_start)
      return 0;
  }
}

/*
 * Try for the next field of a pair, and return a frame formed therefrom
 *
 * - `context` is the context information needed to allow us to find
 *   successive access units.
 * - `quiet` is true if we should try to be silent about it
 * - `show_details` is true if we should output more info than normal
 * - if `first_time` is true, then we will try to match a second field
 *   with a third, if the second field has a different temporal reference
 *   than the first. If it is false, we will not (thus stopping us from
 *   trying forever...)
 * - `picture` starts out at the first field of our (hoped for) pair, and
 *   will end up as the merged result of our two fields. If the input stream
 *   is awry (or we are misaligned with respect to it), this might instead be
 *   replaced by a "proper" frame.
 *
 * Returns 0 if it succeeds, EOF if there is no more data to read, or 1 if
 * some error occurs.
 */
static int get_next_field_of_pair(access_unit_context_p  context,
                                  int                    quiet,
                                  int                    show_details,
                                  int                    first_time,
                                  access_unit_p         *access_unit)
{
  int  err;
  access_unit_p  second;

  if (show_details || context->nac->show_nal_details)
    fprint_msg("@@ Looking for second field (%s time)\n",
               (first_time?"first":"second"));
  
  // We assume (hope) the next picture will be our second half
  err = get_next_non_empty_access_unit(context,quiet,show_details,&second);
  if (err)
  {
    if (err != EOF)
      print_err("### Trying to read second field\n");
    return err;
  }
  
  if (second->field_pic_flag == 0)
  {
    if (!quiet)
      print_err("!!! Field followed by a frame - ignoring the field\n");
    free_access_unit(access_unit);
    *access_unit = second;
    // and pretend to success
  }
  else if ((*access_unit)->frame_num == second->frame_num)
  {
    // They appear to be matching fields - make a frame from them
    if (show_details || context->nac->show_nal_details)
      print_msg("@@ Merging two field access units\n");
    err = merge_access_unit_nals(*access_unit,&second); // (frees `second`)
    if (err)
    {
      free_access_unit(&second);
      return 1;
    }
    if (show_details)
      report_access_unit(*access_unit);
  }
  else if (first_time)
  {
    if (!quiet)
      fprint_err("!!! Field with frame number %d (%x) followed by"
                 " field with frame number %d (%x) - ignoring first field\n",
                 (*access_unit)->frame_num,(*access_unit)->frame_num,
                 second->frame_num,second->frame_num);

    // Try again
    free_access_unit(access_unit);
    *access_unit = second;
    err = get_next_field_of_pair(context,quiet,show_details,FALSE,access_unit);
    if (err) return 1;
  }
  else
  {
    print_err("### Adjacent fields do not share frame numbers"
              " - unable to match fields up\n");
    return 1;
  }
  return 0;
}

/*
 * Retrieve the next H.264 frame from the given elementary stream.
 *
 * The next access unit is retrieved from the input stream (using
 * get_next_access_unit).
 *
 * If that access unit represents a frame, it is returned.
 *
 * If it represents a field, then the *following* access unit is retrieved,
 * and if that is the second field of its frame, it is merged into the first,
 * and the resultant frame is returned.
 *
 * If a field with frame number A is followed by a field with frame number B,
 * it is assumed that synchronisation has been lost. In this case, the first
 * field (frame A) will be discarded, and an attempt made to read the second
 * field of frame B.
 *
 * Similarly, if a frame is found instead of the second field, the first
 * field will be discarded and the frame returned.
 *
 *   Note that if the context is associated with a reverse context,
 *   then appropriate frames will automatically be remembered therein.
 *
 * - `context` is the context information needed to allow us to find
 *   successive access units.
 * - `quiet` is true if we should try to be silent about it
 * - `show_details` is true if we should output more info than normal
 * - `frame` is an access unit datastructure representing the next
 *   frame.
 *
 * If the access unit was ended because an end of sequence or end of
 * stream NAL unit was encountered, then said end of sequence/stream
 * NAL unit will be remembered in the `context`.
 *
 * Returns 0 if it succeeds, EOF if there is no more data to read, or 1 if
 * some error occurs.
 *
 * EOF can be returned because the end of file has been reached, or because an
 * end of stream NAL unit has been encountered. The two may be distinguished
 * by looking at `context->end_of_stream`, which will be NULL if it was a true
 * EOF.
 *
 * Note that `ret_access_unit` will be NULL if EOF is returned.
 */
extern int get_next_h264_frame(access_unit_context_p context,
                               int                   quiet,
                               int                   show_details,
                               access_unit_p        *frame)
{
  int  err;
  access_unit_p  access_unit;

  *frame = NULL;

  err = get_next_non_empty_access_unit(context,quiet,show_details,
                                       &access_unit);
  if (err) return err;

  if (access_unit->field_pic_flag == 1)
  {
    // We assume (hope) the next access_unit will be our second half
    // - let's try to get it, and merge it into our current access unit
    err = get_next_field_of_pair(context,quiet,show_details,TRUE,&access_unit);
    if (err)
    {
      free_access_unit(&access_unit);
      return 1;
    }
  }

  if (context->reverse_data)
  {
    err = maybe_remember_access_unit(context->reverse_data,access_unit,
                                     show_details);
    if (err)
    {
      free_access_unit(&access_unit);
      return 1;
    }
  }
  *frame = access_unit;
  return 0;
}

/*
 * If this access unit was read from PES, did any of its PES packets contain
 * a PTS?
 *
 * Returns TRUE if so, FALSE if not.
 */
extern int access_unit_has_PTS(access_unit_p access_unit)
{
  // We need to look at each ES unit (within each NAL unit) of this access unit
  int ii;
  for (ii=0; ii<access_unit->nal_units->length; ii++)
  {
    if (access_unit->nal_units->array[ii]->unit.PES_had_PTS)
      return TRUE;
  }
  return FALSE;
}

// Local Variables:
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 2
// End:
// vim: set tabstop=8 shiftwidth=2 expandtab: