File: netcam_rtsp.c

package info (click to toggle)
motion 4.1.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,288 kB
  • sloc: ansic: 22,373; sh: 321; makefile: 176
file content (1321 lines) | stat: -rw-r--r-- 50,635 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
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
/***********************************************************
 *  In the top section are the functions that are used
 *  when processing the camera feed.  Since these functions
 *  are internal to the RTSP module, and many require FFmpeg
 *  structures in their declarations, they are within the
 *  HAVE_FFMPEG block that eliminates them entirely when
 *  FFmpeg is not present.
 *
 *  The functions:
 *      netcam_rtsp_setup
 *      netcam_rtsp_next
 *      netcam_rtsp_cleanup
 *  are called from video_common.c therefore must be defined even
 *  if FFmpeg is not present.  They must also not have FFmpeg
 *  structures in the declarations.  Simple error
 *  messages are raised if called when no FFmpeg is found.
 *
 *  Additional note:  Although this module is called netcam_rtsp,
 *  it actually handles more camera types than just rtsp.
 *  Within its current construct, it could be set up to handle
 *  whatever types of capture devices that ffmpeg can use.
 *  As of this writing it includes rtsp, http and v4l2.
 *
 ***********************************************************/

#include <stdio.h>
#include "rotate.h"    /* already includes motion.h */
#include "netcam_rtsp.h"
#include "video_v4l2.h"  /* Needed to validate palette for v4l2 via netcam */

#ifdef HAVE_FFMPEG

#include "ffmpeg.h"

static int netcam_rtsp_check_pixfmt(rtsp_context *rtsp_data){
    /* Determine if the format is YUV420P */
    int retcd;

    retcd = -1;
    if ((rtsp_data->codec_context->pix_fmt == MY_PIX_FMT_YUV420P) ||
        (rtsp_data->codec_context->pix_fmt == MY_PIX_FMT_YUVJ420P)) retcd = 0;

    return retcd;

}

static void netcam_rtsp_set_time(struct timeval *timevar){

    /* We consolidate the calls to get time here so they all use the same basis */
    /* TODO:  Change to clock_gettime and associated autotool change */
    if (gettimeofday(timevar, NULL) < 0) {
        MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "gettimeofday");
    }

}

static void netcam_rtsp_null_context(rtsp_context *rtsp_data){

    rtsp_data->swsctx         = NULL;
    rtsp_data->swsframe_in    = NULL;
    rtsp_data->swsframe_out   = NULL;
    rtsp_data->frame          = NULL;
    rtsp_data->codec_context  = NULL;
    rtsp_data->format_context = NULL;
    rtsp_data->packet_latest.data  = NULL;

}

static void netcam_rtsp_close_context(rtsp_context *rtsp_data){

    if (rtsp_data->swsctx       != NULL) sws_freeContext(rtsp_data->swsctx);
    if (rtsp_data->swsframe_in  != NULL) my_frame_free(rtsp_data->swsframe_in);
    if (rtsp_data->swsframe_out != NULL) my_frame_free(rtsp_data->swsframe_out);
    if (rtsp_data->frame        != NULL) my_frame_free(rtsp_data->frame);
    if (rtsp_data->codec_context    != NULL) my_avcodec_close(rtsp_data->codec_context);
    if (rtsp_data->format_context   != NULL) avformat_close_input(&rtsp_data->format_context);
    if (rtsp_data->packet_latest.data  != NULL) my_packet_unref(rtsp_data->packet_latest);

    netcam_rtsp_null_context(rtsp_data);

}

/* netcam_rtsp_decode_video
 *
 * Return values:
 *   <0 error
 *   0 invalid but continue
 *   1 valid data
 */
static int netcam_rtsp_decode_video(rtsp_context *rtsp_data){

#if (LIBAVFORMAT_VERSION_MAJOR >= 58) || ((LIBAVFORMAT_VERSION_MAJOR == 57) && (LIBAVFORMAT_VERSION_MINOR >= 41))

    int retcd;
    char errstr[128];

    if (rtsp_data->finish) return 0;   /* This just speeds up the shutdown time */

    retcd = avcodec_send_packet(rtsp_data->codec_context, &rtsp_data->packet_recv);
    if ((rtsp_data->interrupted) || (rtsp_data->finish)) return -1;
    if (retcd < 0 && retcd != AVERROR_EOF){
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Error sending packet to codec: %s", errstr);
        return -1;
    }

    retcd = avcodec_receive_frame(rtsp_data->codec_context, rtsp_data->frame);
    if ((rtsp_data->interrupted) || (rtsp_data->finish)) return -1;

    if (retcd == AVERROR(EAGAIN)) return 0;

    /*
     * At least one netcam (Wansview K1) is known to always send a bogus
     * packet at the start of the stream. Just grin and bear it...
     */
    if (retcd == AVERROR_INVALIDDATA) {
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Ignoring packet with invalid data");
        return 0;
    }

    if (retcd < 0) {
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Error receiving frame from codec: %s", errstr);
        return -1;
    }

    return 1;

#else

    int retcd;
    int check = 0;
    char errstr[128];

    if (rtsp_data->finish) return 0;   /* This just speeds up the shutdown time */

    retcd = avcodec_decode_video2(rtsp_data->codec_context, rtsp_data->frame, &check, &rtsp_data->packet_recv);
    if ((rtsp_data->interrupted) || (rtsp_data->finish)) return -1;

    if (retcd == AVERROR_INVALIDDATA) {
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Ignoring packet with invalid data");
        return 0;
    }

    if (retcd < 0) {
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Error decoding packet: %s",errstr);
        return -1;
    }

    if (check == 0 || retcd == 0) return 0;

    return 1;

#endif

}

static int netcam_rtsp_decode_packet(rtsp_context *rtsp_data){

    int frame_size;
    int retcd;

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    retcd = netcam_rtsp_decode_video(rtsp_data);
    if (retcd <= 0) return retcd;

    frame_size = my_image_get_buffer_size(rtsp_data->codec_context->pix_fmt
                                          ,rtsp_data->codec_context->width
                                          ,rtsp_data->codec_context->height);

    netcam_check_buffsize(rtsp_data->img_recv, frame_size);

    retcd = my_image_copy_to_buffer(rtsp_data->frame
                                    ,(uint8_t *)rtsp_data->img_recv->ptr
                                    ,rtsp_data->codec_context->pix_fmt
                                    ,rtsp_data->codec_context->width
                                    ,rtsp_data->codec_context->height
                                    ,frame_size);
    if ((retcd < 0) || (rtsp_data->interrupted)) {
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error decoding video packet: Copying to buffer");
        return -1;
    }

    rtsp_data->img_recv->used = frame_size;

    return frame_size;
}

static int netcam_rtsp_open_codec(rtsp_context *rtsp_data){

#if (LIBAVFORMAT_VERSION_MAJOR >= 58) || ((LIBAVFORMAT_VERSION_MAJOR == 57) && (LIBAVFORMAT_VERSION_MINOR >= 41))
    int retcd;
    char errstr[128];
    AVStream *st;
    AVCodec *decoder = NULL;

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    retcd = av_find_best_stream(rtsp_data->format_context, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if ((retcd < 0) || (rtsp_data->interrupted)){
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: av_find_best_stream: %s,Interrupt %s"
                   ,rtsp_data->cameratype, errstr, rtsp_data->interrupted ? "True":"False");
        return -1;
    }
    rtsp_data->video_stream_index = retcd;
    st = rtsp_data->format_context->streams[rtsp_data->video_stream_index];

    decoder = avcodec_find_decoder(st->codecpar->codec_id);
    if ((decoder == NULL) || (rtsp_data->interrupted)){
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_find_decoder: Failed,Interrupt %s"
                   ,rtsp_data->cameratype, rtsp_data->interrupted ? "True":"False");
        return -1;
    }

    rtsp_data->codec_context = avcodec_alloc_context3(decoder);
    if ((rtsp_data->codec_context == NULL) || (rtsp_data->interrupted)){
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_alloc_context3: Failed,Interrupt %s"
                   ,rtsp_data->cameratype, rtsp_data->interrupted ? "True":"False");
        return -1;
    }

    retcd = avcodec_parameters_to_context(rtsp_data->codec_context, st->codecpar);
    if ((retcd < 0) || (rtsp_data->interrupted)) {
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_parameters_to_context: %s,Interrupt %s"
                   ,rtsp_data->cameratype, errstr, rtsp_data->interrupted ? "True":"False");
        return -1;
    }
    retcd = avcodec_open2(rtsp_data->codec_context, decoder, NULL);
    if ((retcd < 0) || (rtsp_data->interrupted)){
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_open2: %s,Interrupt %s"
                   ,rtsp_data->cameratype, errstr, rtsp_data->interrupted ? "True":"False");
        return -1;
    }

    return 0;
#else

    int retcd;
    char errstr[128];
    AVStream *st;
    AVCodec *decoder = NULL;

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    retcd = av_find_best_stream(rtsp_data->format_context, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if ((retcd < 0) || (rtsp_data->interrupted)){
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: av_find_best_stream: %s,Interrupt %s"
                   ,rtsp_data->cameratype, errstr, rtsp_data->interrupted ? "True":"False");
        return -1;
    }
    rtsp_data->video_stream_index = retcd;
    st = rtsp_data->format_context->streams[rtsp_data->video_stream_index];

    rtsp_data->codec_context = st->codec;
    decoder = avcodec_find_decoder(rtsp_data->codec_context->codec_id);
    if ((decoder == NULL) || (rtsp_data->interrupted)) {
         MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_find_decoder: Failed,Interrupt %s"
                   ,rtsp_data->cameratype, rtsp_data->interrupted ? "True":"False");
         return -1;
     }
    retcd = avcodec_open2(rtsp_data->codec_context, decoder, NULL);
    if ((retcd < 0) || (rtsp_data->interrupted)){
        av_strerror(retcd, errstr, sizeof(errstr));
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: avcodec_open2: %s,Interrupt %s"
                   ,rtsp_data->cameratype, errstr, rtsp_data->interrupted ? "True":"False");
        return -1;
    }

    return 0;
#endif


}

static rtsp_context *rtsp_new_context(void){
    rtsp_context *ret;

    /* Note that mymalloc will exit on any problem. */
    ret = mymalloc(sizeof(rtsp_context));

    memset(ret, 0, sizeof(rtsp_context));

    return ret;
}

static int netcam_rtsp_interrupt(void *ctx){
    rtsp_context *rtsp_data = ctx;

    if (rtsp_data->finish){
        rtsp_data->interrupted = TRUE;
        return TRUE;
    }

    if (rtsp_data->status == RTSP_CONNECTED) {
        return FALSE;
    } else if (rtsp_data->status == RTSP_READINGIMAGE) {
        netcam_rtsp_set_time(&rtsp_data->interruptcurrenttime);
        if ((rtsp_data->interruptcurrenttime.tv_sec - rtsp_data->interruptstarttime.tv_sec ) > rtsp_data->interruptduration){
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Camera reading (%s) timed out"
                       , rtsp_data->cameratype, rtsp_data->camera_name);
            rtsp_data->interrupted = TRUE;
            return TRUE;
        } else{
            return FALSE;
        }
    } else {
        /* This is for NOTCONNECTED and RECONNECTING status.  We give these
         * options more time because all the ffmpeg calls that are inside the
         * rtsp_connect function will use the same start time.  Otherwise we
         * would need to reset the time before each call to a ffmpeg function.
        */
        netcam_rtsp_set_time(&rtsp_data->interruptcurrenttime);
        if ((rtsp_data->interruptcurrenttime.tv_sec - rtsp_data->interruptstarttime.tv_sec ) > rtsp_data->interruptduration){
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Camera (%s) timed out"
                       , rtsp_data->cameratype, rtsp_data->camera_name);
            rtsp_data->interrupted = TRUE;
            return TRUE;
        } else{
            return FALSE;
        }
    }

    /* should not be possible to get here */
    return FALSE;
}

static int netcam_rtsp_resize(rtsp_context *rtsp_data){

    int      retcd;
    char     errstr[128];
    uint8_t *buffer_out;

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    retcd=my_image_fill_arrays(
        rtsp_data->swsframe_in
        ,(uint8_t*)rtsp_data->img_recv->ptr
        ,rtsp_data->codec_context->pix_fmt
        ,rtsp_data->codec_context->width
        ,rtsp_data->codec_context->height);
    if (retcd < 0) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error allocating picture in: %s", errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    buffer_out=(uint8_t *)av_malloc(rtsp_data->swsframe_size*sizeof(uint8_t));

    retcd=my_image_fill_arrays(
        rtsp_data->swsframe_out
        ,buffer_out
        ,MY_PIX_FMT_YUV420P
        ,rtsp_data->imgsize.width
        ,rtsp_data->imgsize.height);
    if (retcd < 0) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error allocating picture out: %s", errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    retcd = sws_scale(
        rtsp_data->swsctx
        ,(const uint8_t* const *)rtsp_data->swsframe_in->data
        ,rtsp_data->swsframe_in->linesize
        ,0
        ,rtsp_data->codec_context->height
        ,rtsp_data->swsframe_out->data
        ,rtsp_data->swsframe_out->linesize);
    if (retcd < 0) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error resizing/reformatting: %s", errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    retcd=my_image_copy_to_buffer(
         rtsp_data->swsframe_out
        ,(uint8_t *)rtsp_data->img_recv->ptr
        ,MY_PIX_FMT_YUV420P
        ,rtsp_data->imgsize.width
        ,rtsp_data->imgsize.height
        ,rtsp_data->swsframe_size);
    if (retcd < 0) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error putting frame into output buffer: %s", errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }
    rtsp_data->img_recv->used = rtsp_data->swsframe_size;

    av_free(buffer_out);

    return 0;

}

static int netcam_rtsp_read_image(rtsp_context *rtsp_data){

    int  size_decoded;
    int  retcd;
    int  haveimage;
    char errstr[128];
    netcam_buff *xchg;

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    av_init_packet(&rtsp_data->packet_recv);
    rtsp_data->packet_recv.data = NULL;
    rtsp_data->packet_recv.size = 0;

    rtsp_data->interrupted=FALSE;
    netcam_rtsp_set_time(&rtsp_data->interruptstarttime);
    rtsp_data->interruptduration = 10;

    rtsp_data->status = RTSP_READINGIMAGE;
    rtsp_data->img_recv->used = 0;
    size_decoded = 0;
    haveimage = FALSE;

    while ((!haveimage) && (!rtsp_data->interrupted)) {
        retcd = av_read_frame(rtsp_data->format_context, &rtsp_data->packet_recv);
        if ((rtsp_data->interrupted) || (retcd < 0)) {
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: av_read_frame: %s ,Interrupt: %s"
                       ,rtsp_data->cameratype
                       ,errstr, rtsp_data->interrupted ? "True":"False");
            my_packet_unref(rtsp_data->packet_recv);
            netcam_rtsp_close_context(rtsp_data);
            return -1;
        }

        if (rtsp_data->packet_recv.stream_index == rtsp_data->video_stream_index){
            /* For a high resolution pass-through we don't decode the image */
            if ((rtsp_data->high_resolution) && (rtsp_data->passthrough)){
                if (rtsp_data->packet_recv.data != NULL) size_decoded = 1;
            } else {
                size_decoded = netcam_rtsp_decode_packet(rtsp_data);
            }

        }

        if (size_decoded > 0 ){
            haveimage = TRUE;
        } else if (size_decoded == 0){
            /* Did not fail, just didn't get anything.  Try again */
            my_packet_unref(rtsp_data->packet_recv);
            av_init_packet(&rtsp_data->packet_recv);
            rtsp_data->packet_recv.data = NULL;
            rtsp_data->packet_recv.size = 0;
        } else {
            my_packet_unref(rtsp_data->packet_recv);
            netcam_rtsp_close_context(rtsp_data);
            return -1;
        }
    }
    /* Skip status change on our first image to keep the "next" function waiting
     * until the handler thread gets going
     */
    if (!rtsp_data->first_image) rtsp_data->status = RTSP_CONNECTED;


    /* Skip resize/pix format for high pass-through */
    if (!(rtsp_data->high_resolution && rtsp_data->passthrough)){
        if ((rtsp_data->imgsize.width  != rtsp_data->codec_context->width) ||
            (rtsp_data->imgsize.height != rtsp_data->codec_context->height) ||
            (netcam_rtsp_check_pixfmt(rtsp_data) != 0) ){
            if (netcam_rtsp_resize(rtsp_data) < 0) return -1;
        }
    }

    netcam_rtsp_set_time(&rtsp_data->img_recv->image_time);

    pthread_mutex_lock(&rtsp_data->mutex);
        if (rtsp_data->passthrough){
            my_packet_unref(rtsp_data->packet_latest);
            av_init_packet(&rtsp_data->packet_latest);
            rtsp_data->packet_latest.data = NULL;
            rtsp_data->packet_latest.size = 0;

            retcd = my_copy_packet(&rtsp_data->packet_latest, &rtsp_data->packet_recv);
            if ((rtsp_data->interrupted) || (retcd < 0)) {
                av_strerror(retcd, errstr, sizeof(errstr));
                MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: av_copy_packet: %s ,Interrupt: %s"
                           ,rtsp_data->cameratype
                           ,errstr, rtsp_data->interrupted ? "True":"False");
                my_packet_unref(rtsp_data->packet_latest);
                rtsp_data->packet_latest.data = NULL;
                rtsp_data->packet_latest.size = 0;
            }
        }
        xchg = rtsp_data->img_latest;
        rtsp_data->img_latest = rtsp_data->img_recv;
        rtsp_data->img_recv = xchg;
    pthread_mutex_unlock(&rtsp_data->mutex);

    my_packet_unref(rtsp_data->packet_recv);

    return 0;
}

static int netcam_rtsp_resize_ntc(rtsp_context *rtsp_data){

    if ((rtsp_data->finish) || (!rtsp_data->first_image)) return 0;

    if ((rtsp_data->imgsize.width  != rtsp_data->codec_context->width) ||
        (rtsp_data->imgsize.height != rtsp_data->codec_context->height) ||
        (netcam_rtsp_check_pixfmt(rtsp_data) != 0) ){
        MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "");
        MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "****************************************************************");
        MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "The network camera is sending pictures in a different");
        if ((rtsp_data->imgsize.width  != rtsp_data->codec_context->width) ||
            (rtsp_data->imgsize.height != rtsp_data->codec_context->height)) {
            if (netcam_rtsp_check_pixfmt(rtsp_data) != 0) {
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "size than specified in the config and also a ");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "different picture format.  The picture is being");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "transcoded to YUV420P and into the size requested");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "in the config file.  If possible change netcam to");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "be in YUV420P format and the size requested in the");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "config to possibly lower CPU usage.");
            } else {
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "size than specified in the configuration file.");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "The picture is being transcoded into the size ");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "requested in the configuration.  If possible change");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "netcam or configuration to indicate the same size");
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "to possibly lower CPU usage.");
            }
            MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "Netcam: %d x %d => Config: %d x %d"
            ,rtsp_data->codec_context->width,rtsp_data->codec_context->height
            ,rtsp_data->imgsize.width,rtsp_data->imgsize.height);
        } else {
            MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "format than YUV420P.  The image sent is being ");
            MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "trancoded to YUV420P.  If possible change netcam ");
            MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "picture format to YUV420P to possibly lower CPU usage.");
        }
        MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "****************************************************************");
        MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "");
    }

    return 0;

}

static int netcam_rtsp_open_sws(rtsp_context *rtsp_data){

    if (rtsp_data->finish) return -1;   /* This just speeds up the shutdown time */

    rtsp_data->swsframe_in = my_frame_alloc();
    if (rtsp_data->swsframe_in == NULL) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Unable to allocate swsframe_in.");
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    rtsp_data->swsframe_out = my_frame_alloc();
    if (rtsp_data->swsframe_out == NULL) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Unable to allocate swsframe_out.");
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    /*
     *  The scaling context is used to change dimensions to config file and
     *  also if the format sent by the camera is not YUV420.
     */
    rtsp_data->swsctx = sws_getContext(
         rtsp_data->codec_context->width
        ,rtsp_data->codec_context->height
        ,rtsp_data->codec_context->pix_fmt
        ,rtsp_data->imgsize.width
        ,rtsp_data->imgsize.height
        ,MY_PIX_FMT_YUV420P
        ,SWS_BICUBIC,NULL,NULL,NULL);
    if (rtsp_data->swsctx == NULL) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Unable to allocate scaling context.");
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    rtsp_data->swsframe_size = my_image_get_buffer_size(
            MY_PIX_FMT_YUV420P
            ,rtsp_data->imgsize.width
            ,rtsp_data->imgsize.height);
    if (rtsp_data->swsframe_size <= 0) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Error determining size of frame out");
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    /* the image buffers must be big enough to hold the final frame after resizing */
    netcam_check_buffsize(rtsp_data->img_recv, rtsp_data->swsframe_size);
    netcam_check_buffsize(rtsp_data->img_latest, rtsp_data->swsframe_size);

    return 0;

}

static void netcam_rtsp_set_http(rtsp_context *rtsp_data){

    rtsp_data->format_context->iformat = av_find_input_format("mjpeg");
    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting http input_format mjpeg",rtsp_data->cameratype);

}

static void netcam_rtsp_set_rtsp(rtsp_context *rtsp_data){

    if (rtsp_data->rtsp_uses_tcp) {
        av_dict_set(&rtsp_data->opts, "rtsp_transport", "tcp", 0);
        av_dict_set(&rtsp_data->opts, "allowed_media_types", "video", 0);
        if (rtsp_data->status == RTSP_NOTCONNECTED)
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting rtsp transport to tcp",rtsp_data->cameratype);
    } else {
        av_dict_set(&rtsp_data->opts, "rtsp_transport", "udp", 0);
        av_dict_set(&rtsp_data->opts, "max_delay", "500000", 0);  /* 100000 is the default */
        if (rtsp_data->status == RTSP_NOTCONNECTED)
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting rtsp transport to tcp",rtsp_data->cameratype);
    }
}

static void netcam_rtsp_set_v4l2(rtsp_context *rtsp_data){

    char optsize[10], optfmt[8], optfps[5];
    char *fourcc;

    rtsp_data->format_context->iformat = av_find_input_format("video4linux2");

    fourcc=malloc(5*sizeof(char));

    v4l2_palette_fourcc(rtsp_data->v4l2_palette, fourcc);

    if (strcmp(fourcc,"MJPG") == 0) {
        sprintf(optfmt, "%s","mjpeg");
        av_dict_set(&rtsp_data->opts, "input_format", optfmt, 0);
    } else if (strcmp(fourcc,"H264") == 0){
        if (v4l2_palette_valid(rtsp_data->path,rtsp_data->v4l2_palette)){
            sprintf(optfmt, "%s","h264");
            av_dict_set(&rtsp_data->opts, "input_format", optfmt, 0);
        } else {
            sprintf(optfmt, "%s","default");
        }
    } else {
        sprintf(optfmt, "%s","default");
    }

    sprintf(optfps, "%d",rtsp_data->frame_limit);
    av_dict_set(&rtsp_data->opts, "framerate", optfps, 0);

    sprintf(optsize, "%dx%d",rtsp_data->imgsize.width,rtsp_data->imgsize.height);
    av_dict_set(&rtsp_data->opts, "video_size", optsize, 0);

    if (rtsp_data->status == RTSP_NOTCONNECTED){
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Requested v4l2_palette option: %d"
                   ,rtsp_data->cameratype,rtsp_data->v4l2_palette);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Requested FOURCC code: %s",rtsp_data->cameratype,fourcc);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting v4l2 input_format %s",rtsp_data->cameratype,optfmt);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting v4l2 framerate %s",rtsp_data->cameratype, optfps);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Setting v4l2 video_size %s",rtsp_data->cameratype, optsize);
    }

    free(fourcc);

}

static void netcam_rtsp_set_path (struct context *cnt, rtsp_context *rtsp_data ) {

    char        *userpass = NULL;
    struct url_t url;

    rtsp_data->path = NULL;

    memset(&url, 0, sizeof(url));

    if (rtsp_data->high_resolution){
        netcam_url_parse(&url, cnt->conf.netcam_highres);
    } else {
        netcam_url_parse(&url, cnt->conf.netcam_url);
    }

    if (cnt->conf.netcam_proxy) {
        MOTION_LOG(WRN, TYPE_NETCAM, NO_ERRNO, "Proxies not supported using for %s",url.service);
    }

    if (cnt->conf.netcam_userpass != NULL) {
        userpass = mystrdup(cnt->conf.netcam_userpass);
    } else if (url.userpass != NULL) {
        userpass = mystrdup(url.userpass);
    }

    if (strcmp(url.service, "v4l2") == 0) {
        rtsp_data->path = mymalloc(strlen(url.path));
        sprintf(rtsp_data->path, "%s",url.path);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Setting up v4l2 via ffmpeg netcam");
    } else {
        if (!strcmp(url.service, "mjpeg")) {
            sprintf(url.service, "%s","http");
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Setting up http via ffmpeg netcam");
        } else {
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Setting up %s via ffmpeg netcam",url.service);
        }
        if (userpass != NULL) {
            rtsp_data->path = mymalloc(strlen(url.service) + 3 + strlen(userpass)
                  + 1 + strlen(url.host) + 6 + strlen(url.path) + 2 );
            sprintf((char *)rtsp_data->path, "%s://%s@%s:%d%s",
                    url.service, userpass, url.host, url.port, url.path);
        } else {
            rtsp_data->path = mymalloc(strlen(url.service) + 3 + strlen(url.host)
                  + 6 + strlen(url.path) + 2);
            sprintf((char *)rtsp_data->path, "%s://%s:%d%s", url.service,
                url.host, url.port, url.path);
        }
    }

    sprintf(rtsp_data->service, "%s",url.service);

    sprintf(rtsp_data->service, "%s",url.service);

    netcam_url_free(&url);
    if (userpass) free (userpass);

}

static void netcam_rtsp_set_parms (struct context *cnt, rtsp_context *rtsp_data ) {
    /* Set the parameters to be used with our camera */

    if (rtsp_data->high_resolution) {
        rtsp_data->imgsize.width = 0;
        rtsp_data->imgsize.height = 0;
        sprintf(rtsp_data->cameratype, "%s","High resolution");
    } else {
        rtsp_data->imgsize.width = cnt->conf.width;
        rtsp_data->imgsize.height = cnt->conf.height;
        sprintf(rtsp_data->cameratype, "%s","Normal resolution");
    }
    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Setting up %s stream.",rtsp_data->cameratype);

    util_check_passthrough(cnt); /* In case it was turned on via webcontrol */
    rtsp_data->status = RTSP_NOTCONNECTED;
    rtsp_data->rtsp_uses_tcp =cnt->conf.rtsp_uses_tcp;
    rtsp_data->v4l2_palette = cnt->conf.v4l2_palette;
    rtsp_data->frame_limit = cnt->conf.frame_limit;
    rtsp_data->camera_name = cnt->conf.camera_name;
    rtsp_data->img_recv = mymalloc(sizeof(netcam_buff));
    rtsp_data->img_recv->ptr = mymalloc(NETCAM_BUFFSIZE);
    rtsp_data->img_latest = mymalloc(sizeof(netcam_buff));
    rtsp_data->img_latest->ptr = mymalloc(NETCAM_BUFFSIZE);
    rtsp_data->handler_finished = TRUE;
    rtsp_data->first_image = TRUE;
    sprintf(rtsp_data->threadname, "%s","Unknown");
    netcam_rtsp_set_time(&rtsp_data->interruptstarttime);
    netcam_rtsp_set_time(&rtsp_data->interruptcurrenttime);
    rtsp_data->interruptduration = 5;
    rtsp_data->passthrough = util_check_passthrough(cnt);
    rtsp_data->interrupted = FALSE;
    netcam_rtsp_set_path(cnt, rtsp_data);

}

static int netcam_rtsp_set_dimensions (struct context *cnt) {

    cnt->imgs.width = 0;
    cnt->imgs.height = 0;
    cnt->imgs.size_norm = 0;
    cnt->imgs.motionsize = 0;

    cnt->imgs.width_high  = 0;
    cnt->imgs.height_high = 0;
    cnt->imgs.size_high   = 0;

    if (cnt->conf.width % 8) {
        MOTION_LOG(CRT, TYPE_NETCAM, NO_ERRNO, "Image width (%d) requested is not modulo 8.", cnt->conf.width);
        cnt->conf.width = cnt->conf.width - (cnt->conf.width % 8) + 8;
        MOTION_LOG(CRT, TYPE_NETCAM, NO_ERRNO, "Adjusting width to next higher multiple of 8 (%d).", cnt->conf.width);
    }
    if (cnt->conf.height % 8) {
        MOTION_LOG(CRT, TYPE_NETCAM, NO_ERRNO, "Image height (%d) requested is not modulo 8.", cnt->conf.height);
        cnt->conf.height = cnt->conf.height - (cnt->conf.height % 8) + 8;
        MOTION_LOG(CRT, TYPE_NETCAM, NO_ERRNO, "Adjusting height to next higher multiple of 8 (%d).", cnt->conf.height);
    }

    /* Fill in camera details into context structure. */
    cnt->imgs.width = cnt->conf.width;
    cnt->imgs.height = cnt->conf.height;
    cnt->imgs.size_norm = (cnt->conf.width * cnt->conf.height * 3) / 2;
    cnt->imgs.motionsize = cnt->conf.width * cnt->conf.height;
    cnt->imgs.type = VIDEO_PALETTE_YUV420P;

    return 0;
}

static int netcam_rtsp_open_context(rtsp_context *rtsp_data){

    int  retcd;
    char errstr[128];

    if (rtsp_data->finish) return -1;

    if (rtsp_data->path == NULL) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "Null path passed to connect");
        }
        return -1;
    }

    rtsp_data->opts = NULL;
    rtsp_data->format_context = avformat_alloc_context();
    rtsp_data->format_context->interrupt_callback.callback = netcam_rtsp_interrupt;
    rtsp_data->format_context->interrupt_callback.opaque = rtsp_data;
    rtsp_data->interrupted = FALSE;

    netcam_rtsp_set_time(&rtsp_data->interruptstarttime);
    rtsp_data->interruptduration = 20;

    if (strncmp(rtsp_data->service, "http", 4) == 0 ){
        netcam_rtsp_set_http(rtsp_data);
    } else if (strncmp(rtsp_data->service, "rtsp", 4) == 0 ){
        netcam_rtsp_set_rtsp(rtsp_data);
    } else if (strncmp(rtsp_data->service, "rtmp", 4) == 0 ){
        netcam_rtsp_set_rtsp(rtsp_data);
    } else if (strncmp(rtsp_data->service, "v4l2", 4) == 0 ){
        netcam_rtsp_set_v4l2(rtsp_data);
    } else {
        av_dict_free(&rtsp_data->opts);
        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Invalid camera service", rtsp_data->cameratype);
        return -1;
    }
    /*
     * There is not many av functions above this (av_dict_free?) but we are not getting clean
     * interrupts or shutdowns via valgrind and they all point to issues with the avformat_open_input
     * right below so we make sure that we are not in a interrupt / finish situation before calling it
     */
    if ((rtsp_data->interrupted) || (rtsp_data->finish) ){
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unable to open camera(%s)"
                       , rtsp_data->cameratype, rtsp_data->camera_name);
        }
        av_dict_free(&rtsp_data->opts);
        if (rtsp_data->interrupted) netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    retcd = avformat_open_input(&rtsp_data->format_context, rtsp_data->path, NULL, &rtsp_data->opts);
    if ((retcd < 0) || (rtsp_data->interrupted) || (rtsp_data->finish) ){
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unable to open camera(%s): %s"
                       , rtsp_data->cameratype, rtsp_data->camera_name, errstr);
        }
        av_dict_free(&rtsp_data->opts);
        if (rtsp_data->interrupted) netcam_rtsp_close_context(rtsp_data);
        return -1;
    }
    av_dict_free(&rtsp_data->opts);
    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Opened camera(%s)", rtsp_data->cameratype, rtsp_data->camera_name);

    /* fill out stream information */
    retcd = avformat_find_stream_info(rtsp_data->format_context, NULL);
    if ((retcd < 0) || (rtsp_data->interrupted) || (rtsp_data->finish) ){
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unable to find stream info: %s"
                       ,rtsp_data->cameratype, errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    /* there is no way to set the avcodec thread names, but they inherit
     * our thread name - so temporarily change our thread name to the
     * desired name */

    util_threadname_get(rtsp_data->threadname);

    util_threadname_set("av",rtsp_data->threadnbr,rtsp_data->camera_name);

    retcd = netcam_rtsp_open_codec(rtsp_data);

    util_threadname_set(NULL, 0, rtsp_data->threadname);

    if ((retcd < 0) || (rtsp_data->interrupted) || (rtsp_data->finish) ){
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            av_strerror(retcd, errstr, sizeof(errstr));
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unable to open codec context: %s"
                       ,rtsp_data->cameratype, errstr);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    if (rtsp_data->codec_context->width <= 0 ||
        rtsp_data->codec_context->height <= 0) {
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Camera image size is invalid",rtsp_data->cameratype);
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    if (rtsp_data->high_resolution){
        rtsp_data->imgsize.width = rtsp_data->codec_context->width;
        rtsp_data->imgsize.height = rtsp_data->codec_context->height;
    }

    rtsp_data->frame = my_frame_alloc();
    if (rtsp_data->frame == NULL) {
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unable to allocate frame.",rtsp_data->cameratype);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    if (netcam_rtsp_open_sws(rtsp_data) < 0) return -1;

    av_init_packet(&rtsp_data->packet_latest);
    rtsp_data->packet_latest.data = NULL;
    rtsp_data->packet_latest.size = 0;


    /* Validate that the previous steps opened the camera */
    retcd = netcam_rtsp_read_image(rtsp_data);
    if ((retcd < 0) || (rtsp_data->interrupted)){
        if (rtsp_data->status == RTSP_NOTCONNECTED){
            MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Failed to read first image",rtsp_data->cameratype);
        }
        netcam_rtsp_close_context(rtsp_data);
        return -1;
    }

    return 0;

}

static int netcam_rtsp_connect(rtsp_context *rtsp_data){

    if (netcam_rtsp_open_context(rtsp_data) < 0) return -1;

    if (netcam_rtsp_resize_ntc(rtsp_data) < 0 ) return -1;

    if (netcam_rtsp_read_image(rtsp_data) < 0) return -1;

    /* We use the status for determining whether to grab a image from
     * the Motion loop(see "next" function).  When we are initially starting,
     * we open and close the context and during this process we do not want the
     * Motion loop to start quite yet on this first image so we do
     * not set the status to connected
     */
    if (!rtsp_data->first_image) rtsp_data->status = RTSP_CONNECTED;

    MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Camera (%s) connected"
               , rtsp_data->cameratype,rtsp_data->camera_name);

    return 0;
}

static void netcam_rtsp_shutdown(rtsp_context *rtsp_data){

    if (rtsp_data) {
        netcam_rtsp_close_context(rtsp_data);

        if (rtsp_data->path != NULL) free(rtsp_data->path);

        if (rtsp_data->img_latest != NULL){
            free(rtsp_data->img_latest->ptr);
            free(rtsp_data->img_latest);
        }
        if (rtsp_data->img_recv != NULL){
            free(rtsp_data->img_recv->ptr);
            free(rtsp_data->img_recv);
        }

        rtsp_data->path    = NULL;
        rtsp_data->img_latest = NULL;
        rtsp_data->img_recv   = NULL;
    }

}

static void *netcam_rtsp_handler(void *arg){

    rtsp_context *rtsp_data = arg;

    rtsp_data->handler_finished = FALSE;

    util_threadname_set("nc",rtsp_data->threadnbr, rtsp_data->camera_name);

    pthread_setspecific(tls_key_threadnr, (void *)((unsigned long)rtsp_data->threadnbr));

    MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Camera handler thread [%d] started"
               ,rtsp_data->cameratype, rtsp_data->threadnbr);

    while (!rtsp_data->finish) {
        if (!rtsp_data->format_context) {      /* We must have disconnected.  Try to reconnect */
            if ((rtsp_data->status == RTSP_CONNECTED) ||
                (rtsp_data->status == RTSP_READINGIMAGE)){
                MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Reconnecting with camera....",rtsp_data->cameratype);
            }
            rtsp_data->status = RTSP_RECONNECTING;
            netcam_rtsp_connect(rtsp_data);
            continue;
        } else {            /* We think we are connected...*/
            if (netcam_rtsp_read_image(rtsp_data) < 0) {
                if (!rtsp_data->finish) {
                    /* Nope.  We are not or got bad image.  Reconnect*/
                    if ((rtsp_data->status == RTSP_CONNECTED) ||
                        (rtsp_data->status == RTSP_READINGIMAGE)){
                        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Bad image.  Reconnecting with camera...."
                                   ,rtsp_data->cameratype);
                    }
                    rtsp_data->status = RTSP_RECONNECTING;
                    netcam_rtsp_connect(rtsp_data);
                }
                continue;
            }
        }
    }

    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Handler loop finished.",rtsp_data->cameratype);
    netcam_rtsp_shutdown(rtsp_data);

    /* Our thread is finished - decrement motion's thread count. */
    pthread_mutex_lock(&global_lock);
        threads_running--;
    pthread_mutex_unlock(&global_lock);

    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "netcam camera handler: finish set, exiting");
    rtsp_data->handler_finished = TRUE;

    pthread_exit(NULL);
}

static int netcam_rtsp_start_handler(rtsp_context *rtsp_data){

    int retcd;
    int wait_counter;
    pthread_attr_t handler_attribute;

    pthread_mutex_init(&rtsp_data->mutex, NULL);

    pthread_attr_init(&handler_attribute);
    pthread_attr_setdetachstate(&handler_attribute, PTHREAD_CREATE_DETACHED);

    pthread_mutex_lock(&global_lock);
        rtsp_data->threadnbr = ++threads_running;
    pthread_mutex_unlock(&global_lock);

    retcd = pthread_create(&rtsp_data->thread_id, &handler_attribute, &netcam_rtsp_handler, rtsp_data);
    if (retcd < 0) {
        MOTION_LOG(ALR, TYPE_NETCAM, SHOW_ERRNO, "%s: Error starting handler thread",rtsp_data->cameratype);
        pthread_attr_destroy(&handler_attribute);
        return -1;
    }
    pthread_attr_destroy(&handler_attribute);


    /* Now give a few tries to check that an image has been captured.
     * This ensures that by the time the setup routine exits, the
     * handler is completely set up and has images available
     */
    wait_counter = 60;
    while (wait_counter > 0) {
        pthread_mutex_lock(&rtsp_data->mutex);
            if (rtsp_data->img_latest->ptr != NULL ) wait_counter = -1;
        pthread_mutex_unlock(&rtsp_data->mutex);

        if (wait_counter > 0 ){
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Waiting for first image from the handler.",rtsp_data->cameratype);
            SLEEP(0,5000000);
            wait_counter--;
        }
    }

    return 0;

}

/*********************************************************
 *  This ends the section of functions that rely upon FFmpeg
 ***********************************************************/
#endif /* End HAVE_FFMPEG */


int netcam_rtsp_setup(struct context *cnt){
#ifdef HAVE_FFMPEG

    int retcd;
    int indx_cam, indx_max;
    rtsp_context *rtsp_data;


    cnt->rtsp = NULL;
    cnt->rtsp_high = NULL;

    if (netcam_rtsp_set_dimensions(cnt) < 0 ) return -1;

    indx_cam = 1;
    indx_max = 1;
    if (cnt->conf.netcam_highres) indx_max = 2;

    while (indx_cam <= indx_max){
        if (indx_cam == 1){
            cnt->rtsp = rtsp_new_context();
            if (cnt->rtsp == NULL) {
                MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "unable to create rtsp context");
                return -1;
            }
            rtsp_data = cnt->rtsp;
            rtsp_data->high_resolution = FALSE;           /* Set flag for this being the normal resolution camera */
        } else {
            cnt->rtsp_high = rtsp_new_context();
            if (cnt->rtsp_high == NULL) {
                MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "unable to create rtsp high context");
                return -1;
            }
            rtsp_data = cnt->rtsp_high;
            rtsp_data->high_resolution = TRUE;            /* Set flag for this being the high resolution camera */
        }

        netcam_rtsp_null_context(rtsp_data);

        netcam_rtsp_set_parms(cnt, rtsp_data);

        if (netcam_rtsp_connect(rtsp_data) < 0) return -1;

        retcd = netcam_rtsp_read_image(rtsp_data);
        if (retcd < 0){
            MOTION_LOG(CRT, TYPE_NETCAM, NO_ERRNO, "Failed trying to read first image - retval:%d", retcd);
            rtsp_data->status = RTSP_NOTCONNECTED;
            return -1;
        }
        /* When running dual, there seems to be contamination across norm/high with codec functions. */
        netcam_rtsp_close_context(rtsp_data);       /* Close in this thread to open it again within handler thread */
        rtsp_data->status = RTSP_RECONNECTING;      /* Set as reconnecting to avoid excess messages when starting */
        rtsp_data->first_image = FALSE;             /* Set flag that we are not processing our first image */

        /* For normal resolution, we resize the image to the config parms so we do not need
         * to set the dimension parameters here (it is done in the set_parms).  For high res
         * we must get the dimensions from the first image captured
         */
        if (rtsp_data->high_resolution){
            cnt->imgs.width_high = rtsp_data->imgsize.width;
            cnt->imgs.height_high = rtsp_data->imgsize.height;
        }

        if (netcam_rtsp_start_handler(rtsp_data) < 0 ) return -1;

        indx_cam++;
    }

    return 0;

#else  /* No FFmpeg/Libav */
    /* Stop compiler warnings */
    if (cnt)
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "FFmpeg/Libav not found on computer.  No RTSP support");
    return -1;
#endif /* End #ifdef HAVE_FFMPEG */
}

int netcam_rtsp_next(struct context *cnt, struct image_data *img_data){
#ifdef HAVE_FFMPEG
    /* This is called from the motion loop thread */
    int  retcd;
    char errstr[128];

    if ((cnt->rtsp->status == RTSP_RECONNECTING) ||
        (cnt->rtsp->status == RTSP_NOTCONNECTED)) return 1;
    pthread_mutex_lock(&cnt->rtsp->mutex);
        if (cnt->rtsp->passthrough){
            if ((!cnt->rtsp->interrupted) && (cnt->rtsp->packet_latest.data != NULL)) {
                my_packet_unref(img_data->packet_norm);
                av_init_packet(&img_data->packet_norm);
                img_data->packet_norm.data = NULL;
                img_data->packet_norm.size = 0;

                retcd = my_copy_packet(&img_data->packet_norm, &cnt->rtsp->packet_latest);
                if (retcd < 0) {
                    av_strerror(retcd, errstr, sizeof(errstr));
                    MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: av_copy_packet: %s",cnt->rtsp->cameratype,errstr);
                    img_data->packet_norm.data = NULL;
                    img_data->packet_norm.size = 0;
                    pthread_mutex_unlock(&cnt->rtsp->mutex);
                    return 1;  /* Non fatal bad image */
                }
            }
        }
        memcpy(img_data->image_norm, cnt->rtsp->img_latest->ptr, cnt->rtsp->img_latest->used);
    pthread_mutex_unlock(&cnt->rtsp->mutex);

    if (cnt->rtsp_high){
        if ((cnt->rtsp_high->status == RTSP_RECONNECTING) ||
            (cnt->rtsp_high->status == RTSP_NOTCONNECTED)) return 1;
        pthread_mutex_lock(&cnt->rtsp_high->mutex);
            if (cnt->rtsp_high->passthrough){
                if ((!cnt->rtsp_high->interrupted) && (cnt->rtsp_high->packet_latest.data != NULL)) {
                    my_packet_unref(img_data->packet_high);
                    av_init_packet(&img_data->packet_high);
                    img_data->packet_high.data = NULL;
                    img_data->packet_high.size = 0;

                    retcd = my_copy_packet(&img_data->packet_high, &cnt->rtsp_high->packet_latest);
                    if (retcd < 0) {
                        av_strerror(retcd, errstr, sizeof(errstr));
                        MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: av_copy_packet: %s",cnt->rtsp_high->cameratype,errstr);
                        img_data->packet_high.data = NULL;
                        img_data->packet_high.size = 0;
                        pthread_mutex_unlock(&cnt->rtsp_high->mutex);
                        return 1;
                    }
                }
            }
            memcpy(img_data->image_high, cnt->rtsp_high->img_latest->ptr, cnt->rtsp_high->img_latest->used);
        pthread_mutex_unlock(&cnt->rtsp_high->mutex);
    }

    /* Rotate images if requested */
    rotate_map(cnt, img_data);

    return 0;

#else  /* No FFmpeg/Libav */
    /* Stop compiler warnings */
    if ((cnt) || (img_data))
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "FFmpeg/Libav not found on computer.  No RTSP support");
    return -1;
#endif /* End #ifdef HAVE_FFMPEG */
}

void netcam_rtsp_cleanup(struct context *cnt, int init_retry_flag){
#ifdef HAVE_FFMPEG
     /*
     * If the init_retry_flag is not set this function was
     * called while retrying the initial connection and there is
     * no camera-handler started yet and thread_running must
     * not be decremented.
     */
    int wait_counter;
    int indx_cam, indx_max;
    rtsp_context *rtsp_data;

    indx_cam = 1;
    indx_max = 1;
    if (cnt->rtsp_high) indx_max = 2;

    while (indx_cam <= indx_max) {
        if (indx_cam == 1){
            rtsp_data = cnt->rtsp;
        } else {
            rtsp_data = cnt->rtsp_high;
        }

        if (rtsp_data){
            MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Shutting down network camera.",rtsp_data->cameratype);

            /* Throw the finish flag in context and wait a bit for it to finish its work and close everything
             * This is shutting down the thread so for the moment, we are not worrying about the
             * cross threading and protecting these variables with mutex's
            */
            rtsp_data->finish = TRUE;
            rtsp_data->interruptduration = 0;
            wait_counter = 0;
            while ((!rtsp_data->handler_finished) && (wait_counter < 10)) {
                SLEEP(1,0);
                wait_counter++;
            }
            if (!rtsp_data->handler_finished) {
                MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: No response from handler thread.",rtsp_data->cameratype);
                /* Last resort.  Kill the thread. Not safe for posix.  Uncomment if we must later...*/
                /* pthread_kill(rtsp_data->thread_id); */
                pthread_cancel(rtsp_data->thread_id);
                if (!init_retry_flag){
                    pthread_mutex_lock(&global_lock);
                        threads_running--;
                    pthread_mutex_unlock(&global_lock);
                }
            }
            /* If we never connect we don't have a handler but we still need to clean up some */
            netcam_rtsp_shutdown(rtsp_data);

            pthread_mutex_destroy(&rtsp_data->mutex);

            free(rtsp_data);
            rtsp_data = NULL;
            if (indx_cam == 1){
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "Normal resolution: Shut down complete.");
            } else {
                MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "High resolution: Shut down complete.");
            }
        }
        indx_cam++;
    }

#else  /* No FFmpeg/Libav */
    /* Stop compiler warnings */
    if ((cnt) || (init_retry_flag))
        MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "FFmpeg/Libav not found on computer.  No RTSP support");
    return;
#endif /* End #ifdef HAVE_FFMPEG */

}