TsFileSource.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using MatrixIO.IO.MpegTs;
  10. namespace TsViewer
  11. {
  12. public class TsFileSource : TsSource
  13. {
  14. private Thread _readThread;
  15. private volatile bool _running;
  16. public TsFileSource() { }
  17. ~TsFileSource()
  18. {
  19. Stop();
  20. }
  21. public void Start(string path)
  22. {
  23. Start(new Uri(path));
  24. }
  25. public override void Start(Uri uri)
  26. {
  27. Uri = uri;
  28. _running = true;
  29. _readThread = new Thread(ReadFile);
  30. _readThread.Start(this);
  31. }
  32. public override void Stop()
  33. {
  34. if (!_running) return;
  35. Debug.WriteLine("Stopping background thread.");
  36. _running = false;
  37. if (_readThread.Join(1000)) return;
  38. _readThread.Abort();
  39. }
  40. private enum TsStreamType
  41. {
  42. Standard,
  43. AACS,
  44. ATSC_FEC,
  45. }
  46. private void ReadFile(object data)
  47. {
  48. try
  49. {
  50. var fileStream = File.Open(Uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  51. int packetLength = TsPacket.Length;
  52. var type = TsStreamType.Standard;
  53. if (Uri.LocalPath.EndsWith(".m2ts", true, CultureInfo.InvariantCulture))
  54. {
  55. packetLength = AacsPacket.Length;
  56. type = TsStreamType.AACS;
  57. }
  58. var buffer = new byte[packetLength*7];
  59. int length;
  60. do
  61. {
  62. if ((length = fileStream.Read(buffer, 0, buffer.Length)) <= 0) continue;
  63. switch (type)
  64. {
  65. case TsStreamType.Standard:
  66. Debug.WriteLine("Read " + length + " bytes from " +
  67. Uri.Segments[Uri.Segments.Length - 1] + " with a first byte of 0x" +
  68. buffer[0].ToString("X2"));
  69. Demuxer.ProcessInput(buffer, 0, length);
  70. break;
  71. case TsStreamType.AACS:
  72. for (int i = 0; i < length/packetLength; i++)
  73. {
  74. var packet = new AacsPacket(buffer, i*packetLength);
  75. Debug.WriteLine("Read AACS Packet");
  76. Demuxer.ProcessPacket(packet.TsPacket);
  77. }
  78. break;
  79. }
  80. } while (length > 0 && _running);
  81. fileStream.Close();
  82. }
  83. finally
  84. {
  85. _running = false;
  86. }
  87. }
  88. }
  89. }