using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.src.Mpeg2.PacketFilter
{
    [PluginPriority(999)]
    public class TeiOnOffFilter : BasePacketFilter
    {
        public TeiOnOffFilter()
        {
            state = new bool?[8192];
            suspicions = new byte[8192];
        }
        private bool?[] state;
        private byte[] suspicions;
        private const byte LIMIT = 3;

        protected override bool PassPacketEx(TsPacket packet)
        {
            bool scrambled = packet.TSC != 0;

            if (!state[packet.PID].HasValue)
            {
                state[packet.PID] = scrambled;
                return true;
            }

            if (suspicions[packet.PID] >= LIMIT)
            {
                return false;
            }

            if (state[packet.PID].Value != scrambled)
            {
                if (scrambled)
                    suspicions[packet.PID]++;

                state[packet.PID] = scrambled;
            }

            return true;
        }
    }
}
