forked from ArduPilot/MissionPlanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OSDVideo.cs
771 lines (603 loc) · 24.9 KB
/
OSDVideo.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Drawing.Imaging;
using System.Collections;
using System.IO;
using DirectShowLib;
using AviFile;
namespace ArdupilotMega
{
public partial class OSDVideo : Form, ISampleGrabberCB
{
public Dictionary<DateTime, CurrentState> flightdata = new Dictionary<DateTime, CurrentState>();
public DateTime startlogtime = DateTime.MinValue;
public DateTime videopos = DateTime.MinValue;
CurrentState cs = new CurrentState();
AviManager newManager;
VideoStream newStream;
static int frame = 0;
//double framerate = 0;
static int framecount = 0;
//static bool play = true;
//static bool stop = false;
bool fullresolution = false;
static System.Threading.Thread th;
/// <summary> graph builder interface. </summary>
private IFilterGraph2 m_FilterGraph = null;
private IMediaControl m_mediaCtrl = null;
IAMExtendedSeeking m_mediaextseek = null;
IMediaPosition m_mediapos = null;
IMediaSeeking m_mediaseek = null;
/// <summary> so we can wait for the async job to finish </summary>
private ManualResetEvent m_PictureReady = null;
/// <summary> Set by async routine when it captures an image </summary>
private volatile bool m_bGotOne = false;
/// <summary> Indicates the status of the graph </summary>
private bool m_bRunning = false;
/// <summary> Dimensions of the image, calculated once in constructor. </summary>
public IntPtr m_handle = IntPtr.Zero;
private int m_videoWidth;
private int m_videoHeight;
private int m_stride;
public int m_Dropped = 0;
public Bitmap image = null;
IntPtr ip = IntPtr.Zero;
public bool DSplugin = false;
Bitmap trans = new Bitmap(5,5,PixelFormat.Format32bppArgb);
Thread timer1;
public string textbox { set { textBox1.Text = value; } }
public OSDVideo()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
hud1.SixteenXNine = true;
}
void OSDVideo_camimage(Image camimage)
{
// camimage = new Bitmap(640, 480, PixelFormat.Format32bppArgb);
hud1.bgimage = camimage;// new Bitmap(camimage, hud1.Size);
//Application.DoEvents();
}
private void saveconfig()
{
try
{
using (StreamWriter sw = new StreamWriter(Path.GetDirectoryName(txtAviFileName.Text) + Path.DirectorySeparatorChar + "osdvideo.txt"))
{
sw.WriteLine(txtAviFileName.Text);
sw.WriteLine(txt_tlog.Text);
sw.WriteLine(trackBar1.Value);
sw.Close();
}
}
catch { }
}
private void loadconfig()
{
try
{
using (StreamReader sr = new StreamReader(Path.GetDirectoryName(txtAviFileName.Text) + Path.DirectorySeparatorChar + "osdvideo.txt"))
{
txtAviFileName.Text = sr.ReadLine();
txt_tlog.Text = sr.ReadLine();
trackBar1.Value = int.Parse(sr.ReadLine());
sr.Close();
}
}
catch { }
}
private void startup()
{
dolog();
if (DSplugin)
{
timer1 = new Thread(timer);
timer1.IsBackground = true;
timer1.Start();
return;
}
try
{
th.Abort();
}
catch { }
th = new System.Threading.Thread(delegate() { StartCapture(); });
th.Name = "Video Thread";
th.Start();
}
public void writeconsole(string input)
{
Console.WriteLine(input);
}
public Bitmap gethud(Bitmap bmpin, double time)
{
// stop it from drawing
hud1.HoldInvalidation = true;
// update bg to be trans
hud1.bgimage = trans;
// use gdi
hud1.opengl = false;
// resize
hud1.Width = bmpin.Width;
hud1.Height = bmpin.Height;
// makesure we can grab an image
hud1.streamjpgenable = true;
// redraw
hud1.Refresh();
// clone current screen with trans
return (Bitmap)hud1.objBitmap.Clone();
}
private void StartCapture()
{
int hr;
ISampleGrabber sampGrabber = null;
IBaseFilter capFilter = null;
ICaptureGraphBuilder2 capGraph = null;
if (System.IO.File.Exists(txtAviFileName.Text))
{
// Get the graphbuilder object
m_FilterGraph = (IFilterGraph2)new FilterGraph();
m_mediaCtrl = m_FilterGraph as IMediaControl;
// Get the ICaptureGraphBuilder2
capGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
// Get the SampleGrabber interface
sampGrabber = (ISampleGrabber)new SampleGrabber();
// Start building the graph
hr = capGraph.SetFiltergraph(m_FilterGraph);
DsError.ThrowExceptionForHR(hr);
// Add the video source
hr = m_FilterGraph.AddSourceFilter(txtAviFileName.Text, "File Source (Async.)", out capFilter);
DsError.ThrowExceptionForHR(hr);
//add AVI Decompressor
IBaseFilter pAVIDecompressor = (IBaseFilter)new AVIDec();
hr = m_FilterGraph.AddFilter(pAVIDecompressor, "AVI Decompressor");
DsError.ThrowExceptionForHR(hr);
IBaseFilter ffdshow;
try
{
// Create Decoder filter COM object (ffdshow video decoder)
Type comtype = Type.GetTypeFromCLSID(new Guid("{04FE9017-F873-410E-871E-AB91661A4EF7}"));
if (comtype == null)
throw new NotSupportedException("Creating ffdshow video decoder COM object fails.");
object comobj = Activator.CreateInstance(comtype);
ffdshow = (IBaseFilter)comobj; // error ocurrs! raised exception
comobj = null;
}
catch { CustomMessageBox.Show("Please install/reinstall ffdshow"); return; }
hr = m_FilterGraph.AddFilter(ffdshow, "ffdshow");
DsError.ThrowExceptionForHR(hr);
//
IBaseFilter baseGrabFlt = (IBaseFilter)sampGrabber;
ConfigureSampleGrabber(sampGrabber);
// Add the frame grabber to the graph
hr = m_FilterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber");
DsError.ThrowExceptionForHR(hr);
IBaseFilter vidrender = (IBaseFilter) new VideoRenderer();
hr = m_FilterGraph.AddFilter(vidrender, "Render");
DsError.ThrowExceptionForHR(hr);
IPin captpin = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0);
IPin ffdpinin = DsFindPin.ByName(ffdshow, "In");
IPin ffdpinout = DsFindPin.ByName(ffdshow, "Out");
IPin samppin = DsFindPin.ByName(baseGrabFlt, "Input");
hr =m_FilterGraph.Connect(captpin,ffdpinin);
DsError.ThrowExceptionForHR(hr);
hr = m_FilterGraph.Connect(ffdpinout, samppin);
DsError.ThrowExceptionForHR(hr);
FileWriter filewritter = new FileWriter();
IFileSinkFilter filemux = (IFileSinkFilter)filewritter;
//filemux.SetFileName("test.avi",);
//hr = capGraph.RenderStream(null, MediaType.Video, capFilter, null, vidrender);
// DsError.ThrowExceptionForHR(hr);
SaveSizeInfo(sampGrabber);
// setup buffer
if (m_handle == IntPtr.Zero)
m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight);
// tell the callback to ignore new images
m_PictureReady = new ManualResetEvent(false);
m_bGotOne = false;
m_bRunning = false;
timer1 = new Thread(timer);
timer1.IsBackground = true;
timer1.Start();
m_mediaextseek = m_FilterGraph as IAMExtendedSeeking;
m_mediapos = m_FilterGraph as IMediaPosition;
m_mediaseek = m_FilterGraph as IMediaSeeking;
double length = 0;
m_mediapos.get_Duration(out length);
trackBar_mediapos.Minimum = 0;
trackBar_mediapos.Maximum = (int)length;
Start();
}
else
{
MessageBox.Show("File does not exist");
}
}
void dolog()
{
flightdata.Clear();
MAVLink mine = new MAVLink();
try
{
mine.logplaybackfile = new BinaryReader(File.Open(txt_tlog.Text, FileMode.Open, FileAccess.Read, FileShare.Read));
}
catch { CustomMessageBox.Show("Log Can not be opened. Are you still connected?"); return; }
mine.logreadmode = true;
mine.MAV.packets.Initialize(); // clear
mine.readPacket();
startlogtime = mine.lastlogread;
double oldlatlngsum = 0;
int appui = 0;
while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
{
byte[] packet = mine.readPacket();
cs.datetime = mine.lastlogread;
cs.UpdateCurrentSettings(null, true, mine);
if (appui != DateTime.Now.Second)
{
// cant do entire app as mixes with flightdata timer
this.Refresh();
appui = DateTime.Now.Second;
}
try
{
if (MainV2.speechEngine != null)
MainV2.speechEngine.SpeakAsyncCancelAll();
}
catch { } // ignore because of this Exception System.PlatformNotSupportedException: No voice installed on the system or none available with the current security setting.
// if ((float)(cs.lat + cs.lng + cs.alt) != oldlatlngsum
// && cs.lat != 0 && cs.lng != 0)
DateTime nexttime = mine.lastlogread.AddMilliseconds(-(mine.lastlogread.Millisecond % 100));
if (!flightdata.ContainsKey(nexttime))
{
Console.WriteLine(cs.lat + " " + cs.lng + " " + cs.alt + " lah " + (float)(cs.lat + cs.lng + cs.alt) + "!=" + oldlatlngsum);
CurrentState cs2 = (CurrentState)cs.Clone();
try
{
flightdata.Add(nexttime, cs2);
}
catch { }
oldlatlngsum = (cs.lat + cs.lng + cs.alt);
}
}
mine.logreadmode = false;
mine.logplaybackfile.Close();
mine.logplaybackfile = null;
}
public void timer()
{
Control.CheckForIllegalCrossThreadCalls = false;
videopos = startlogtime.AddMilliseconds(-startlogtime.Millisecond);
hud1.SixteenXNine = true;
while (true)
{
try
{
// GC.Collect();
// long mem = GC.GetTotalMemory(true) / 1024 / 1024;
// Console.WriteLine("mem "+mem);
System.Threading.Thread.Sleep(20); // 25 fps
if (flightdata.Count == 0)
break;
// videopos = videopos.AddMilliseconds(1000 / 25);
// m_mediaseek = m_FilterGraph as IMediaSeeking;
// m_mediapos.put_CurrentPosition((vidpos - startlogtime).TotalSeconds);
//m_mediaseek.SetTimeFormat(TimeFormat.MediaTime);
//long poscurrent = 0;
//long posend = 0;
// m_mediaseek.GetPositions(out poscurrent,out posend);
DateTime cstimestamp = videopos.AddSeconds(trackBar1.Value).AddMilliseconds(-(videopos.Millisecond % 20));
int tb = trackBar1.Value;
if (flightdata.ContainsKey(cstimestamp))
{
cs = flightdata[cstimestamp];
}
else if (flightdata.ContainsKey(cstimestamp.AddMilliseconds(-20)))
{
cs = flightdata[cstimestamp.AddMilliseconds(-20)];
}
else if (flightdata.ContainsKey(cstimestamp.AddMilliseconds(-40)))
{
cs = flightdata[cstimestamp.AddMilliseconds(-40)];
}
// Console.WriteLine("Update CS");
Console.WriteLine("log "+ cs.datetime);
hud1.datetime = cs.datetime;
cs.UpdateCurrentSettings(bindingSource1);
}
catch (ThreadAbortException)
{
break;
}
catch
{
}
}
}
public int Stride
{
get
{
return m_stride;
}
}
/// <summary> capture the next image </summary>
public IntPtr GetBitMap()
{
if (m_handle == IntPtr.Zero)
m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight);
try
{
// Start waiting
// if (!m_PictureReady.WaitOne(5000, false))
{
//throw new Exception("Timeout waiting to get picture");
}
}
catch
{
Marshal.FreeCoTaskMem(m_handle);
throw;
}
// Got one
return m_handle;
}
// Start the capture graph
public void Start()
{
if (!m_bRunning)
{
int hr = m_mediaCtrl.Run();
DsError.ThrowExceptionForHR(hr);
m_bRunning = true;
}
}
// Pause the capture graph.
// Running the graph takes up a lot of resources. Pause it when it
// isn't needed.
public void Pause()
{
if (m_bRunning)
{
int hr = m_mediaCtrl.Pause();
DsError.ThrowExceptionForHR(hr);
m_bRunning = false;
}
}
private void SaveSizeInfo(ISampleGrabber sampGrabber)
{
int hr;
// Get the media type from the SampleGrabber
AMMediaType media = new AMMediaType();
hr = sampGrabber.GetConnectedMediaType(media);
DsError.ThrowExceptionForHR(hr);
if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
{
throw new NotSupportedException("Unknown Grabber Media Format");
}
// Grab the size info
VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
m_videoWidth = videoInfoHeader.BmiHeader.Width;
m_videoHeight = videoInfoHeader.BmiHeader.Height;
m_stride = m_videoWidth * (videoInfoHeader.BmiHeader.BitCount / 8);
DsUtils.FreeAMMediaType(media);
media = null;
}
private void ConfigureSampleGrabber(ISampleGrabber sampGrabber)
{
AMMediaType media;
int hr;
// Set the media type to Video/RBG24
media = new AMMediaType();
media.majorType = MediaType.Video;
media.subType = MediaSubType.RGB24;
media.formatType = FormatType.VideoInfo;
sampGrabber.SetBufferSamples(false);
sampGrabber.SetOneShot(false);
hr = sampGrabber.SetMediaType(media);
DsError.ThrowExceptionForHR(hr);
DsUtils.FreeAMMediaType(media);
media = null;
// Configure the samplegrabber
hr = sampGrabber.SetCallback(this, 1);
DsError.ThrowExceptionForHR(hr);
}
private void BUT_vidfile_Click(object sender, EventArgs e)
{
String fileName = GetFileName("Videos (*.avi)|*.avi;*.mpe;*.mpeg;*.mp4", txtAviFileName);
if (fileName != null)
{
// update name before calling next function
txtAviFileName.Text = fileName;
// load setting if they exist
loadconfig();
// force file we just picked as video
txtAviFileName.Text = fileName;
}
}
private String GetFileName(String filter, Control ctl)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = filter;
dlg.RestoreDirectory = true;
if (ctl.Text.Length > 0)
{
dlg.InitialDirectory = GetCurrentFilePath(ctl);
}
if (dlg.ShowDialog(this) == DialogResult.OK)
{
return dlg.FileName;
}
else
{
return null;
}
}
private String GetCurrentFilePath(Control ctl)
{
return ctl.Text.Substring(0, ctl.Text.LastIndexOf("\\") + 1);
}
private void BUT_start_Click(object sender, EventArgs e)
{
saveconfig();
try
{
m_mediaCtrl.Stop();
}
catch { }
try
{
frame = framecount;
th.Abort();
}
catch { }
newManager = new AviManager(System.IO.Path.GetDirectoryName(txtAviFileName.Text) + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(txtAviFileName.Text) + "-overlay.avi", false);
//newManager.Close();
startup();
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
}
private static class NativeMethods
{
[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]
internal static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);
}
/// <summary> sample callback, NOT USED. </summary>
int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
{
if (!m_bGotOne)
{
// Set bGotOne to prevent further calls until we
// request a new bitmap.
m_bGotOne = true;
IntPtr pBuffer;
pSample.GetPointer(out pBuffer);
int iBufferLen = pSample.GetSize();
if (pSample.GetSize() > m_stride * m_videoHeight)
{
throw new Exception("Buffer is wrong size");
}
NativeMethods.CopyMemory(m_handle, pBuffer, m_stride * m_videoHeight);
// Picture is ready.
m_PictureReady.Set();
}
Marshal.ReleaseComObject(pSample);
return 0;
}
/// <summary> buffer callback, COULD BE FROM FOREIGN THREAD. </summary>
int ISampleGrabberCB.BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
{
Console.WriteLine("BufferCB " + DateTime.Now.Millisecond + " pbtime " + SampleTime);
framecount++;
videopos = startlogtime.AddSeconds(SampleTime);
trackBar_mediapos.Value = (int)SampleTime;
// The buffer should be long enought
if (BufferLen <= m_stride * m_videoHeight)
{
// Copy the frame to the buffer
// CopyMemory(m_handle, pBuffer, m_stride * m_videoHeight);
m_handle = pBuffer;
}
else
{
throw new Exception("Buffer is wrong size");
}
try
{
Console.WriteLine("1 " + DateTime.Now.Millisecond);
//ip = this.GetBitMap();
image = new Bitmap(m_videoWidth, m_videoHeight, m_stride, PixelFormat.Format24bppRgb, m_handle);
Console.WriteLine("1a " + DateTime.Now.Millisecond);
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
Console.WriteLine("1b " + DateTime.Now.Millisecond);
hud1.HoldInvalidation = true;
hud1.opengl = true;
hud1.bgimage = image;
hud1.streamjpgenable = true;
if (fullresolution)
{
hud1.Width = image.Width;
hud1.Height = image.Height;
}
Console.WriteLine("1c " + DateTime.Now.Millisecond);
hud1.Refresh();
Console.WriteLine("1d " + DateTime.Now.Millisecond);
Bitmap bmp = (Bitmap)hud1.objBitmap.Clone();
// bmp.Save(framecount+".bmp");
Console.WriteLine("1e " + DateTime.Now.Millisecond);
if (newStream == null)
{
int fixframerate; // currently forcing 30 fps
newStream = newManager.AddVideoStream(true, (double)(int)30, bmp);
}
Console.WriteLine("2 " + DateTime.Now.Millisecond);
addframe(bmp);
lock (avienclock)
{
// System.Threading.ThreadPool.QueueUserWorkItem(addframe, bmp);
}
Console.WriteLine("3 " + DateTime.Now.Millisecond);
}//System.Windows.Forms.CustomMessageBox.Show("Problem with capture device, grabbing frame took longer than 5 sec");
catch (Exception ex) { Console.WriteLine("Grab bmp failed " + ex.ToString()); }
return 0;
}
object avienclock = new object();
void addframe(object bmp) {
lock (avienclock)
{
newStream.AddFrame((Bitmap)bmp);
((Bitmap)bmp).Dispose();
}
}
private void BUT_tlogfile_Click(object sender, EventArgs e)
{
String fileName = GetFileName("Tlog (*.tlog)|*.tlog", txt_tlog);
if (fileName != null)
{
txt_tlog.Text = fileName;
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
hud1.Invalidate();
saveconfig();
}
private void trackBar_mediapos_Scroll(object sender, EventArgs e)
{
m_mediapos.put_CurrentPosition((double)trackBar_mediapos.Value);
}
private void OSDVideo_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
flightdata.Clear();
th.Abort();
}
catch { }
try
{
m_mediaCtrl.Stop();
}
catch { }
try
{
System.Threading.Thread.Sleep(500);
newManager.Close();
th.Abort();
}
catch { }
}
private void CHK_fullres_CheckedChanged(object sender, EventArgs e)
{
fullresolution = CHK_fullres.Checked;
}
}
}